Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 424
xSeder Avatar asked Oct 22 '10 22:10

xSeder


1 Answers

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> 
like image 135
John Bowen Avatar answered Oct 05 '22 10:10

John Bowen