I have a class that contains multiple collections of properties:
class Foo{
public ObservableCollection<Bar> Bars {get; set;}
public ObservableCollection<Baz> Bazzes {get; set;}
}
I'm trying to display this in a TreeView, where the Foo node is at the root, and then under it is a node for the Bars collection containing each of the Bar elements as subnodes, and the same for the Bazzes collection. But I can't seem to get the data template right. The closest I've managed to get is like so:
<HierarchicalDataTemplate DataType="{x:Type local:Foo}">
<TreeViewItem Header="Root">
<TreeViewItem Header="Bars" ItemsSource="{Binding Path=Bars}"/>
<TreeViewItem Header="Bazzes" ItemsSource="{Binding Path=Bazzes}"/>
</TreeViewItem>
</HierarchicalDataTemplate>
<DataTemplate DataType="{x:Type local:Bar}">
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding Name}" />
<TextBlock Text=" (" Foreground="Blue" />
<TextBlock Text="{Binding Type}" Foreground="Blue" />
<TextBlock Text=")" Foreground="Blue" />
</StackPanel>
</DataTemplate>
<DataTemplate DataType="{x:Type local:Baz}">
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding Name}" />
</StackPanel>
</DataTemplate>
This displays a hierarchical tree with nodes I can open to display sub-items by clicking the little triangle, but when I try to click on any of the items, it selects the entire Foo with all of its sub-items as one big selection. I'm assuming this is because the nodes containing the collections are integrated into the template for Foo and so it's treating them as all being one big node somehow? But I don't know how to get the collections to show up as sub-nodes without doing it that way.
What's the correct way to do the type of setup I'm looking for, since this is obviously not quite right?
There are a couple of fundamental issues with your implementation. The first is that the Tree is simply a map onto the bound data structure which is expected to be a tree. First we have to make your Foo class a tree...
Next we need a different template for each type of tree node. We therefore need a data template selector
Finally we are ready to pull everything together in XAML...
A few loose ends...
This is the result...