WPF: How do I use two different controls in an ItemsControl?
I have a WPF control that has an ItemsSource bound to an observable collection of view models in MVVM. The ItemTemplate is set to the custom control I want. However, there are cases where I need a different control than the one specified in the XAML.
How can i do this?
+2
bluebit
source
to share
2 answers
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>
+9
Kent boogaart
source
to share
If I understand that you have a collection containing two different object types and you want to use two different templates. You can create a datatemplate for each object type and leave WPF to render the correct template based on the object type.
+1
ema
source
to share