TL;DR up front: I would like to use a “default” HierarchicalDataTemplate for all but a specific few nodes in a WPF TreeView. These nodes come from an XMLDocument and are not fully known until runtime. Is there a way to do this?
At runtime, I am analyzing specific parts of a system, and building an XML document that I’m then binding to a TreeView like so:
MyTree.DataContext = MyXMLDocument;
This is my WPF declaration of the TreeView:
<TreeView x:Name="MyTree" ItemsSource="{Binding Mode=OneWay, XPath=/Analysis}" ItemTemplate="{StaticResource GenericElementWithChildren}"/>
The template starts like this…
<HierarchicalDataTemplate x:Key="GenericElementWithChildren" ItemsSource="{Binding XPath=child::node()}">
So for example, I might have some long XML document about different aspects of the analysis I just ran and I’d like some particular element like “Disk” or “Proprietary Foo Service” to have a special template because it should be displayed nicely, while everything else just gets a generic template.
I’ve thought about using a DataTemplateSelector but it seems like there must be a better way. I’m not even sure how I’d do that for XML. Do any of you smarter folks have any wisdom to impart, or am I stuck figuring out how to write a DataTemplateSelector against XML?
DataTemplateandHierarchicalDataTemplatealso have aDataTypeproperty.When you remove the
x:Keyand supply aDataType, these Templates are implicit. So you can define your different templates as implicit and they will be used automatically, as long as you don’t supply aItemTemplateorItemTemplateSelectoron the initalTreeView.Personally i try to avoid that, because this also means that other controls that can show your data are using these Templates aswell. Imo the best would be to use a
DataTemplateSelector, especially when you deal with the same types that you need to show in different ways.Edit:
Sorry i missed that you are using Xpath. I guess it will not work there. I will leave this answer here, but can’t guarantee that it suits your needs. Maybe it helps in another way anyway.