Linking to "IsExpanded" doesn't work for root node in TreeView

I have one TreeView

that will display several different data types in an arbitrary hierarchy. To do this, I define specific HierarchicalDataTemplate

for each data type that will be placed in mine 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), so I define different HierarchicalDataTemplate

for each type.

The binding IsExpanded

does not work as I expect. The root node is TreeView

never expanded regardless of the property value of the original object IsObjectExpanded

. The masking node works as expected.

Also, if I hard-bind a property IsExpanded

to True

in the root node definition HierarchicalDataTemplate

(if I know what type it will be in the root of the tree), its children appear extended, rather than the root node.

Am I using the property correctly IsExpanded

? Or is there another way that I should set the property IsExpanded

to include the root node?

+3


source to share


1 answer


HierarchicalDataTemplate.ItemContainerStyle

sets the style for the children of the element you are declaring the template for. If you need to style the root, you can use TreeView.ItemContainerStyle

.



If you feel limited by this architecture (which is admittedly stupid), you can use HierarchicalDataTemplate.ItemContainerStyleSelector

.

+4


source







All Articles