Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/wpf/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 基于类型选择数据模板_C#_Wpf_Xaml_Mvvm_Datatemplate - Fatal编程技术网

C# 基于类型选择数据模板

C# 基于类型选择数据模板,c#,wpf,xaml,mvvm,datatemplate,C#,Wpf,Xaml,Mvvm,Datatemplate,我声明了以下类型: public interface ITest { } public class ClassOne : ITest { } public class ClassTwo : ITest { } 在我的viewmodel中,我声明并初始化以下集合: public class ViewModel { public ObservableCollection<ITest> Coll { get; set; } = new ObservableCollection&l

我声明了以下类型:

public interface ITest { }
public class ClassOne : ITest { }
public class ClassTwo : ITest { }
在我的viewmodel中,我声明并初始化以下集合:

public class ViewModel
{
    public ObservableCollection<ITest> Coll { get; set; } = new ObservableCollection<ITest>
    {
        new ClassOne(),
        new ClassTwo()
    };  
}
我希望看到的是一个红方块,后面跟着一个蓝方块,而我看到的是:


我做错了什么?

您的问题可能是由XAML的finnicky工作引起的。具体来说,您需要将
类型
传递到
数据类型
,但传递的是一个带有类型名称的字符串

使用
x:Type
装饰
DataType
的值,如下所示:

<ItemsControl ItemsSource="{Binding Coll}">
    <ItemsControl.Resources>
        <DataTemplate DataType="{x:Type local:ClassOne}">
            <Rectangle Width="50" Height="50" Fill="Red" />
        </DataTemplate>
        <DataTemplate DataType="{x:Type local:ClassTwo}">
            <Rectangle Width="50" Height="50" Fill="Blue" />
        </DataTemplate>
    </ItemsControl.Resources>
</ItemsControl>


我想你实际上想要@ChrisW。直接从该链接:"... 如果同一类型的对象有多个DataTemplate,并且希望提供自己的逻辑来根据每个数据对象的属性选择要应用的DataTemplate,请创建DataTemplateSelector。请注意,如果您有不同类型的对象,则可以在DataTemplate上设置DataType属性。“对不起,伙计,我在想,反正我可能不应该在这里,自从冬天以来的第一个美好的一天,我的思想在别处,我甚至不认为我真的看了整个问题,哈哈。春天的狂热,干杯。你也可以使用DataTemplateSelector。非常好用,谢谢,但是您省略了大括号({x:Type local:ClassOne})。知道我使用的东西为什么不起作用吗?@kyriacos_k Yours不起作用,因为
DataTemplate.DataType
属性的类型为
object
(与
Style.TargetType
相反,后者的类型为
type
)。因此,
local:ClassOne
被解释为字符串,而不是隐式转换为
Type
x:Type
的行为就像
typeof()
操作符一样,因此您传递给
DataType
一个
Type
,而不是类的名称。-即使声明它使用
object
,示例也不使用
x:Type
<ItemsControl ItemsSource="{Binding Coll}">
    <ItemsControl.Resources>
        <DataTemplate DataType="{x:Type local:ClassOne}">
            <Rectangle Width="50" Height="50" Fill="Red" />
        </DataTemplate>
        <DataTemplate DataType="{x:Type local:ClassTwo}">
            <Rectangle Width="50" Height="50" Fill="Blue" />
        </DataTemplate>
    </ItemsControl.Resources>
</ItemsControl>