I have created several DataTemplates for some of the DataTypes in my pet project. These data templates are really cool as they work like magic, magically transforming the look of the instances of the data types whenever and wherever they show up in the UI. Now I want to be able to change the DataTemplate for these DataTypes in one particular ListBox. Does this mean I have to stop relying on WPF automatically applying the data template to the data types and assign a x:Key to the DataTemplates and then apply the Template/ItemTemplate in the UI using that key?
A ListBox contains items of various DataTypes (all derived from a common base class) and as it is now, all magically works without specifying a TemplateSelector, as the correct template is chosen by the actual data type of the item in the listBox. If I went for using the x:Key to apply DataTemplates, would I then need to write a TemplateSelector?
I am new to this and only experimenting with DataTemplates. One moment I think, wow, how cool! And then I want a different data template for the same data type in a different list box and ooops, I can't do it :-) Help please?
You can specify an
ItemTemplate
specifically for yourListBox
:Or alternatively, if you have already defined your
DataTemplate
in aResourceDictionary
somewhere:Then you can reference it on the
ListBox
using:You do not need to write a template selector for either of these approaches to work
Example in response to comments
The example below demonstrates defining a default
DataTemplate
for a data type (in this case,String
) for a window and then overridding it within a listbox:This produces the following UI: