views:

28

answers:

2

Hello everyone, I've got the problem with displaying wpf listbox items.

I give abstract example. I hope it's going to be ok.

I've got a class FruitViewModel - it describes viewmodels for listboxitems.

And I've got

class BananaViewModel : FruitViewModel

and

class AppleViewModel : FruitViewModel

So, collection Fruits contains BananaViewModels and AppleViewModels. And this collection is bound to ItemsSource.

And here I've got such a question:

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

+1  A: 

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

Reddog
+2  A: 

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>
John Bowen
Good stuff, thank you!
xSeder