two itemtemplates for one listbox
Asked Answered
O

2

42

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

Odo answered 22/10, 2010 at 22:54 Comment(0)
F
81

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>
Felicitous answered 23/10, 2010 at 1:59 Comment(2)
Thanks for mentioning that you must omit the x:Key!Countermove
If you want to have the 2 DataTemplates in your <Window.Resources>. How do you set the 'ItemTemplate=' Property to multiple DataTemplates? Especially I want to outsource 2 HierarchicalDataTemplates for a TreeView to the <Window.Resources>. Multibinding could be a solution.Mediatize
C
3

On the ListView in XAML you can declare an ItemTemplateSelector. The value for this will come from a static resource or similar.

The implementation of your template selector should implement DataTemplateSelector and will basically contain the 'if' statement that chooses the correct DataTemplate based on the bound item's type. It will likely find the DataTemplate from the passed in container's resources (probably using the FindResource function).

Edit: Good link perhaps? http://www.switchonthecode.com/tutorials/wpf-tutorial-how-to-use-a-datatemplateselector Dead link.

Clarion answered 22/10, 2010 at 23:3 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.