ksk*_*cou 10 c# wpf xaml datatemplate mvvm
我已经声明了以下类型:
public interface ITest { }
public class ClassOne : ITest { }
public class ClassTwo : ITest { }
Run Code Online (Sandbox Code Playgroud)
在我的viewmodel中,我正在声明并初始化以下集合:
public class ViewModel
{
public ObservableCollection<ITest> Coll { get; set; } = new ObservableCollection<ITest>
{
new ClassOne(),
new ClassTwo()
};
}
Run Code Online (Sandbox Code Playgroud)
在我看来,我宣布以下内容 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>
Run Code Online (Sandbox Code Playgroud)
我期待看到的是一个红色方块,后面是一个蓝色方块,而我所看到的是以下内容:
我究竟做错了什么?
Ama*_*rek 17
您的问题可能是由XAML的辛苦工作引起的.具体来说,您需要传递Type给DataType,但是您传递的是具有该类型名称的字符串.
使用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>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6015 次 |
| 最近记录: |