1

I have a strange WPF/XAML problem. By default, I want all of the nodes in this TreeView to be expanded. Eventually I'll bind it to my view model, but right now I just want them all expanded by default.

This is the part of the code in question (that I am currently using)

<HierarchicalDataTemplate DataType="{x:Type Model:DirectoryItem}"
                          ItemsSource="{Binding Items}">
    <TextBlock Text="{Binding Path=Name}"
               ToolTip="{Binding Path=Path}" />
    <HierarchicalDataTemplate.ItemContainerStyle>   
        <Style TargetType="TreeViewItem">
            <Setter Property="IsExpanded" Value="True" />
        </Style> 
    </HierarchicalDataTemplate.ItemContainerStyle>
</HierarchicalDataTemplate>

<DataTemplate DataType="{x:Type Model:FileItem}">
    <TextBlock Text="{Binding Path=Name}"
               ToolTip="{Binding Path=Path}" />
</DataTemplate>

In particular, the part where I have the setter property as IsExpanded.

As you can see by the images below, this code is sort-of working. If I expand the root nodes, then everything is expanded by default.

But why are the root nodes not expanded by default as well? I have no idea why it is doing this.

enter image description here enter image description here

1 Answer 1

1

They aren't expanded probably because you're adding the style to the Hierarchical Data Template and that applies to children only (only theory, though).

Using styles in DataTemplate is a kind of code smell - it's a template for data, not the visual representation, so it shouldn't contain the style for treeViewItem (it may be something else next time, also hierarchical).

I'd suppose you do it like this:

<TreeView.ItemContainerStyle>
            <Style TargetType="TreeViewItem">
                <Setter Property="TreeViewItem.IsExpanded" Value="True"/>
            </Style>
 </TreeView.ItemContainerStyle>
2
  • Thanks, that worked. Thank you for the explanation as well. I do have a follow up question though (I am quite new to WPF) - if I'm not placing it in the Hierarchical Data Template, in the future will I still be able to bind it to the IsExpanded property in the DirectoryItem object? Thanks
    – theqs1000
    Mar 31, 2012 at 12:44
  • You can use {Binding YourPropertyName} instead of "True" in current solution. Mar 31, 2012 at 12:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.