我有一个 xaml 页面,上面有一个 ItemsControl 控件。 ItemsControl 绑定(bind)到 Guests,即 ObservableCollection。 Guests 集合可以有两种不同类型的对象:USGuest 和 UKGuest,它们都继承自 Guest。是否可以为 ItemsControl 制作两个(或更多)模板并使其根据集合中当前项目的运行时类型自动在它们之间进行选择?
最佳答案
我还没有尝试过这个,但是您是否尝试过将 ItemsSource 设置为 Guest 对象的 ObservableCollection 并为这两种类型设置 DataTemplate?
<DataTemplate DataType="{x:Type my:USGuestViewModel}">
<my:USGuestView/>
</DataTemplate>
<DataTemplate DataType="{x:Type my:UKGuestViewModel}">
<my:UKGuestView/>
</DataTemplate>
编辑:“我的”是您的 ViewModel 和 View 所在的命名空间的声明,因此您应该在 xaml 的开头添加类似这样的内容:
<UserControl x:Class="my.namespace.SuperView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:my="clr-namespace:my.namespace">
我已经检查过,您不能在 ItemTemplate 属性中设置两个 DataTemplate。但是您可以在您的 UserControl 资源属性中设置它们:
<UserControl.Resources>
<DataTemplate DataType="{x:Type my:USGuestViewModel}">
<my:USGuestView/>
</DataTemplate>
<DataTemplate DataType="{x:Type my:UKGuestViewModel}">
<my:UKGuestView/>
</DataTemplate>
</UserControl.Resources>
关于wpf - 如何使 ItemsControl 根据运行时类型选择不同的模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3132885/