I've declared the following types:
我已经宣布了以下类型:
public interface ITest { }
public class ClassOne : ITest { }
public class ClassTwo : ITest { }
In my viewmodel I'm declaring and initializing the following collection:
在我的viewmodel中,我正在声明并初始化以下集合:
public class ViewModel
{
public ObservableCollection<ITest> Coll { get; set; } = new ObservableCollection<ITest>
{
new ClassOne(),
new ClassTwo()
};
}
In my view I'm declaring the following ItemsControl
在我看来,我正在声明以下ItemsControl
<ItemsControl ItemsSource="{Binding Coll}">
<ItemsControl.Resources>
<DataTemplate DataType="local:ClassOne">
<Rectangle Width="50" Height="50" Fill="Red" />
</DataTemplate>
<DataTemplate DataType="local:ClassTwo">
<Rectangle Width="50" Height="50" Fill="Blue" />
</DataTemplate>
</ItemsControl.Resources>
</ItemsControl>
What I expect to see is a red square followed by a blue square, instead what I see is the following:
我希望看到的是一个红色方块,后面是一个蓝色方块,而我所看到的是以下内容:
What am I doing wrong?
我究竟做错了什么?
2 个解决方案
#1
7
Your issue might be caused by finnicky workings of XAML. Specifically, you need to pass Type
to DataType
, but you were passing a string with the name of the type.
您的问题可能是由XAML的辛苦工作引起的。具体来说,您需要将Type传递给DataType,但是您传递的是具有该类型名称的字符串。
Use x:Type
to decorate the value of DataType
, like so:
使用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>
#2
#1
7
Your issue might be caused by finnicky workings of XAML. Specifically, you need to pass Type
to DataType
, but you were passing a string with the name of the type.
您的问题可能是由XAML的辛苦工作引起的。具体来说,您需要将Type传递给DataType,但是您传递的是具有该类型名称的字符串。
Use x:Type
to decorate the value of DataType
, like so:
使用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>