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 BananaViewModel
s and AppleViewModel
s 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
You can define DataTemplates that apply to any instance of a specific type by specifying the
DataType
without anx:Key
. Using this method you don't assign anything toItemTemplate
- the templates are applied automatically.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 theFindResource
function).Edit: Good link perhaps? http://www.switchonthecode.com/tutorials/wpf-tutorial-how-to-use-a-datatemplateselectorDead link.