如何使ItemsControl根据运行时类型选择不同的模板

dur*_*rad 1 silverlight wpf itemscontrol mvvm

我有一个xaml页面,上面有一个ItemsControl控件.ItemsControl绑定到ObservableCollection的Guests.来宾集合可以包含两种不同类型的对象:USGuest和UKGuest,两者都继承自Guest.是否可以为ItemsControl创建两个(或更多)模板,并根据集合中当前项的运行时类型自动选择它们?

jps*_*res 7

我没试过这个,但是你试过将ItemsSource设置为Guest对象的ObservableCollection并为两种类型设置DataTemplate吗?

<DataTemplate DataType="{x:Type my:USGuestViewModel}">
    <my:USGuestView/>
</DataTemplate>
<DataTemplate DataType="{x:Type my:UKGuestViewModel}">
    <my:UKGuestView/>
</DataTemplate>
Run Code Online (Sandbox Code Playgroud)

编辑:'my'是ViewModel和Views所在的命名空间的声明,所以你应该在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">
Run Code Online (Sandbox Code Playgroud)

我已经检查过,你不能在ItemTemplate属性中设置两个DataTemplates.但您可以在UserControl Resources属性中设置它们:

<UserControl.Resources>
    <DataTemplate DataType="{x:Type my:USGuestViewModel}">
        <my:USGuestView/>
    </DataTemplate>
    <DataTemplate DataType="{x:Type my:UKGuestViewModel}">
        <my:UKGuestView/>
    </DataTemplate>
</UserControl.Resources>
Run Code Online (Sandbox Code Playgroud)