Search code examples
wpfmvvmitemscontrol

WPF: How do I use two different controls in an ItemsControl?


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?


Solution

  • 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>