R – WPF: How to use two different controls in an ItemsControl

itemscontrolmvvmwpf

I have a WPF ItemsControl who's ItemsSource is bound to an observable collection of view models in MVVM. The ItemTemplate is set to the user control that I want. However, there are instances when I would like another control instead of the one specified in XAML.

How can I easily do this?

Best Answer

Use DataTemplates to map view models to views:

<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>
Related Topic