wpfxamltreeviewhierarchicaldatatemplateitemcontainerstyle

TreeView HierarchicalDataTemplate does not apply ItemContainerStyle


I try do display hierarchical data with a TreeView and I would like to set different DataTemplates for my different Children types.

But the thing is, that my style does not get applied.

Maybe its a very simple mistake but i really do not find it.

<TreeView ItemsSource="{Binding List}">
    <TreeView.Resources>
        <HierarchicalDataTemplate DataType="{x:Type local:Main}" ItemsSource="{Binding Children}">
            <TextBlock Text="{Binding Property1}"/>
        </HierarchicalDataTemplate>
        <HierarchicalDataTemplate DataType="{x:Type local:Type2}">
            <HierarchicalDataTemplate.ItemContainerStyle>
                <Style TargetType="TreeViewItem">
                    <Setter Property="IsExpanded" Value="True"/>
                </Style>
            </HierarchicalDataTemplate.ItemContainerStyle>
            <TextBlock Text="{Binding Property2}"/>
        </HierarchicalDataTemplate>
        <HierarchicalDataTemplate DataType="{x:Type local:Type3}">
            <HierarchicalDataTemplate.ItemContainerStyle>
                <Style TargetType="TreeViewItem">
                    <Setter Property="IsExpanded" Value="False"/>
                </Style>
            </HierarchicalDataTemplate.ItemContainerStyle>
        </HierarchicalDataTemplate>
    </TreeView.Resources>
</TreeView>

Solution

  • Ok, I know what is going wrong. HierarchicalDataTemplate.ItemContainerStyle contains a style which is applied to the ItemsContainer where the children for the current node are stored. Try this as an experiment, change your style to:

        <HierarchicalDataTemplate.ItemContainerStyle>
            <Style TargetType="{x:Type TreeViewItem}">
                <Setter Property="IsExpanded" Value="True" />
                <Setter Property="Foreground" Value="Navy" />
            </Style>
        </HierarchicalDataTemplate.ItemContainerStyle>
    

    You will notice that the node that you put this style onto continues to have a black foreground, but all it's children will now have a foreground of Navy.

    It is a little counter-intuitive, but when you think about it, I guess it makes sense. So, bearing this in mind, I think the best solution is to bind IsExpanded for all TreeViewItems to a variable in the VM and then pick different values based on types there.