I have a TreeView that will display several different datatypes in an arbitrary hierarchy. To accomplish this, I'm defining specific HierarchicalDataTemplate's for each datatype that will be diplayed in my TreeView:
<HierarchicalDataTemplate DataType="{x:Type local:MyFirstType}" ItemsSource="{Binding Children}" >
<HierarchicalDataTemplate.ItemContainerStyle>
<Style TargetType="{x:Type TreeViewItem}">
<Setter Property="IsExpanded" Value="{Binding IsObjectExpanded, Mode=TwoWay}" />
</Style>
</HierarchicalDataTemplate.ItemContainerStyle>
<TextBlock Text="{Binding Name}" />
</HierarchicalDataTemplate>
<HierarchicalDataTemplate DataType="{x:Type local:MySecondType}" ItemsSource="{Binding Children}" >
...
</HierarchicalDataTemplate>
<HierarchicalDataTemplate DataType="{x:Type local:MyThirdType}" ItemsSource="{Binding Children}" >
...
</HierarchicalDataTemplate>
Each HierarchicalDataTemplate will have a slightly different style (not shown above), which is why I'm defining different HierarchicalDataTemplate's for each type.
The IsExpanded binding isn't working the way I expect, however. The root node of the TreeView is never expanded, regardless of the value of the source object's IsObjectExpanded property. The child node bindings are working as expected.
In addition, if I hardcode the IsExpanded property to True in the root node's HierarchicalDataTemplate definition (assuming I know which type will be at the root of the tree), its children show up expanded rather than the root node itself.
Am I using the IsExpanded property correctly? Or is there another way I should be setting the IsExpanded property in order to include the root node?
HierarchicalDataTemplate.ItemContainerStyle sets style for children of the item you declare template for. If you need to set style for the root, you can use TreeView.ItemContainerStyle.
If you feel restricted by this architecture (which is admittedly silly), you can use HierarchicalDataTemplate.ItemContainerStyleSelector.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With