WPF:如何在ItemsControl中使用两个不同的控件?

blu*_*bit 2 wpf itemscontrol mvvm

我有一个WPF ItemsControl,它的ItemsSource绑定到MVVM中可观察的视图模型集合.ItemTemplate设置为我想要的用户控件.但是,有些情况下我想要另一个控件而不是XAML中指定的控件.

我怎么能轻松做到这一点?

Ken*_*art 9

使用DataTemplates将视图模型映射到视图:

<ItemsControl ItemsSource="{Binding SomeCollectionOfViewModels}">
    <ItemsControl.Resources>
        <DataTemplate DataType="{x:Type local:FirstViewModel}">
            <Label>Foo</Label>
        </DataTemplate>

        <DataTemplate DataType="{x:Type local:SecondViewModel}">
            <Label>Bar</Label>
        </DataTemplate>
    </ItemsControl.Resources>
</ItemsControl>
Run Code Online (Sandbox Code Playgroud)