I have a WPF application which uses a TreeView, inside that TreeView there are multiple HierarchicalDataTemplates/DataTemplates for different types, each containing a ContentControl with a specific Template, like so:
TreeView
|- HierarchicalDataTemplate for Type a
| |- ContentControl
|
|- DataTemplate for Type b
|- ContentControl
The type b is built like this:
b
|-integer c
|-object d
d can be anything from an integer to a string, but it can also be a class containing a list. In that case I want to display the list of d using a HierarchicalDataTemplate inside the TreeView described above.
Is there a way to do that, or do I lose all connection to the hierarchy of the TreeView as soon as I enter the DataTemplate/ContentControl/Template?
For complex scenarios like this, you can implement a custom
DataTemplateSelector. From your description I assume a data types like these forAandB, with properties forCandD:You could create custom data templates for each type and purpose. For
B, there would be both aDataTemplatefor the regular types and aHierarchicalDataTemplatefor whenDis a collection:The
x:Keys are needed to resolve to the data templates using theDataTemplateSelector. In this case, we would check if an item is of typeAand use theATemplate. If it isB, we check whether its template needs to be hierarchical or not by inspecting propertyD. If it is a collection - or in more general terms anIEnumerable, we use the hierarchical template. However, be aware that some types likestringare enumberable, too, so we need to make a separate check.Whether you create constants for the template names or build the keys from the type names or expose properties to assign the data templates is up to your requirements.