Different sets of HierarchicalDataTemplates with DataType property for different TreeViews

StackOverflow https://stackoverflow.com/questions/13312259

سؤال

I have a WPF TreeView bound to a hierarchy of objects of mixed types. Therefore, I use HierarchicalDataTemplates with the "DataType" property to specify the template used for each type, which works fine (the TreeView automatically catches the right one for each object type).

Now I have the problem that I have a second TreeView (in the same XAML file) which is to be populated with the same types of objects. This time, however, they have to be displayed in another way, so I need another set of HierarchicalDateTemplates. Again, I would use the "DataType" property. But if I put them in the same XAML file, of course I get an error (that I can't define two templates for the same type).

Is there a way to scope them somehow so the first set is exclusively used by the first TreeView, and the second one only by the second TreeView?

(Note that because the object tree structure is not known in advance, I have to use the "DataType" approach (which I prefer anyway) and can not use a static HierarchicalDataTemplate.)

هل كانت مفيدة؟

المحلول

Put the first DataTemplate set in the resources of your first TreeView, and the second one in the resources of your second TreeView and it should be working.

<TreeView>
    <TreeView.Resources>
        <!-- put your data templates here -->
    </TreeView.Resources>
</TreeView>

See FrameworkElement.Resources for more info.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top