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>