开发者

Overriding default template for specific nodes in a databound (XML/XPath) TreeView

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}" ItemTem开发者_开发知识库plate="{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?


DataTemplate and HierarchicalDataTemplate also have a DataType property. When you remove the x:Key and supply a DataType, 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 a ItemTemplate or ItemTemplateSelector on the inital TreeView.

<HierachicalDataTemplate DataType="{x:Type ProprietaryFooService}">

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜