I have a ListBox and multiple DataTemplates, in separate files.
<ListBox ItemTemplate="{StaticResource ItemTemplate1}"/>
In the Styles.xaml file:
<DataTemplate x:Key="ItemTemplate1">...</DataTemplate>
<DataTemplate x:Key="ItemTemplate2">...</DataTemplate>
I want to change the ItemTemplate of the ListBox depending on the type of object that’s in its list.
Is there a way to access the separate DataTemplates in the code-behind, so that I can bind to a property of my Page?
The way to do that without
TemplateSelectoris to specify DataType property and don’t specify x:Key.In this case appropriate DataTemplate will be automaticly applied in all places where property of specified type have been bound.
But I’d prefer to use
TemplateSelector.To access separated DataTemplate in code-behind you should first get resource dictionary:
Then you can get template: