Expand first level of treeview item or node using WPF

If you recall in a previous article I created a treeview class with checkboxes here. I expanded on that later to include images here.

I realized that I had set the IsExpanded property of the treeview within a setter for my treeview resources with a value of True. This meant that all nodes within the treeview would be expanded. If I set it to False it meant that all child nodes would be closed and we would see only a single line. I didn’t want either. What I wanted was to expand the first level of the treeview by default and leave all other child nodes closed. It turns out it is simple to do this.

image

Within the TreeVIewModel class add a new property named IsNodeExpanded.

public bool IsNodeExpanded { get; private set; }

Within the SetTree method change the value of the IsNodeExpanded property to true. Since the default value for a bool is false, we don’t need to set it for every value being added to the treeview.

tv.IsNodeExpanded = true;

Lastly, modify the XAML code from:

<Setter Property="IsExpanded" Value="True" />

To:

<Setter Property="IsExpanded" Value="{Binding IsNodeExpanded}" />

And the results will be the below. Child nodes are closed and the root node it expanded.

image