Search code examples
wpflistboxitemtemplate

two itemtemplates for one listbox


I've got a class FruitViewModel. It describes ViewModels for ListBox items.

<ListBox ItemsSource="{Binding Fruits}">

And I've got

class BananaViewModel : FruitViewModel

and

class AppleViewModel : FruitViewModel

Fruits contains BananaViewModels and AppleViewModels which is bound to ItemsSource.

How can I make different templates for apples and bananas? They should be in one list but have different templates


Solution

  • You can define DataTemplates that apply to any instance of a specific type by specifying the DataType without an x:Key. Using this method you don't assign anything to ItemTemplate - the templates are applied automatically.

    <ListBox ItemsSource="{Binding Path=MixedList}">
        <ListBox.Resources>
            <DataTemplate DataType="{x:Type local:BananaViewModel}">
                <TextBlock Text="{Binding Name}" Foreground="Yellow"/>
            </DataTemplate>
            <DataTemplate DataType="{x:Type local:AppleViewModel}">
                <TextBlock Text="{Binding Name}" Foreground="Red"/>
            </DataTemplate>
        </ListBox.Resources>
    </ListBox>