#1,219 – Expanding All Nodes in a TreeView by Default

Normally, when you display a TreeView, the nodes are collapsed by default and the user clicks on the expander widgets to expand nodes that they want to look at.

You can expand all nodes in the TreeView by default by setting up an ItemContainerStyle for the TreeView and specifying that you want each TreeViewItem expanded.

Below, we show the first part of a TreeView definition in XAML, referencing an ItemContainerStyle (data templates are not shown).

<TreeView Grid.Row="0" Margin="5" 
          ItemsSource="{Binding Breeds}" 
          ItemContainerStyle="{StaticResource TreeViewItemStyle_ExpandAll}" 
          HorizontalContentAlignment="Stretch">
<!-- remainder of TreeView definition goes here -->

In the style, we simply set the IsExpanded property to true.

<Style x:Key="TreeViewItemStyle_ExpandAll" TargetType="{x:Type TreeViewItem}">
    <Setter Property="IsExpanded" Value="True"/>
</Style>

Now, at runtime, all of the nodes in the TreeView are expanded by default.

#917 – Changing Something when an Expander Is Expanded

You can use a trigger to change some property in an Expander whenever the Expander is expanded.  You set the trigger to react to a change in the IsExpanded property.

In the example below, we define a trigger that changes the border color for any expander that is expanded.

    <Window.Resources>
        <Style x:Key="changeColorOnExpanded" TargetType="Expander">
            <Setter Property="BorderBrush" Value="DarkGray"/>
            <Setter Property="Margin" Value="10,5"/>
            <Style.Triggers>
                <Trigger Property="IsExpanded" Value="True">
                    <Setter Property="BorderBrush" Value="Crimson"/>
                </Trigger>
            </Style.Triggers>
        </Style>
    </Window.Resources>

    <StackPanel>
        <Expander Style="{StaticResource changeColorOnExpanded}"
                  Header="Great Novels">
            <ScrollViewer>
                <StackPanel>
                    <TextBlock Text="Ulysses"/>
                    <TextBlock Text="The Great Gatsby"/>
                    <TextBlock Text="A Portrait of the Artist as a Young Man"/>
                    <TextBlock Text="Lolita"/>
                </StackPanel>
            </ScrollViewer>
        </Expander>
        <Expander Style="{StaticResource changeColorOnExpanded}"
                  Header="Funny Guys">
            <ScrollViewer>
                <StackPanel>
                    <TextBlock Text="Bill Murray"/>
                    <TextBlock Text="Eddie Murphy"/>
                    <TextBlock Text="Will Ferrell"/>
                    <TextBlock Text="John Cleese"/>
                </StackPanel>
            </ScrollViewer>
        </Expander>
    </StackPanel>

917-001