Any way to use interfaces with wpf HierarchicalDat

2019-07-19 12:58发布

问题:

Hi I am using an interface IFooNode, which is part of a tree.
I wanted to display this tree in a TreeView using a HierarchicalDataTemplate. This however does not work due to the interface. I see two ways around that neither are what I would call "nice"

  1. Find out what type really implements IFooNode (let's call it FooNode...), then find the assembly defining FooNode, add a Reference to that assembly and create a HierarchicalDataTemplate for FooNode (hoping the Implementating class never changes...)

  2. Write a class MyCoolIFooNodeWrapperForWpf that wraps IFooNode, do not bind to the tree, but fill a list of MyCoolIFooNodeWrapperForWpf from the tree root and create a HierarchicalDataTemplate for MyCoolIFooNodeWrapperForWpf.

Can I somehow always apply a HierarchicalDataTemplate, no matter what type the data is (This I think would be the lesser evil...)

Any other Ideas?

回答1:

You can use ItemTemplateSelector. In the selector's code you can check which interface your data object implements, and select the appropriate DataTemplate/HeirarchicalDataTemplate for this item.

The selector can both be applied to the container itself (ItemsControl.ItemTemplateSelector) and to your hierarchical data template (HeirarchicalDataTemplate.ItemTemplateSelector).

I think this is the lesser evil.



回答2:

If you're not selecting from among multiple templates, you don't need to specify a data type on the template. If all of the objects in your tree implement your interface, just stick in a template using properties of that interface and you're good to go. You don't need to do anything in the template to make it specific to that interface.

If, for some reason, you need to do template selection based on what interface an object supports, you need to implement a template selector, and deal with the many-to-one problem that prevents WPF's built-in template selection mechanism from using interfaces in the first place. (That is, if you have a template for IFoo and one for IBar, what template do you use for an object that supports IFoo and IBar?)