BlackWaspTM

This web site uses cookies. By using the site you accept the cookie policy.This message is for compliance with the UK ICO law.

Windows Presentation Foundation
.NET 4.0+

WPF Data Display Controls - TreeView - Basics

The one hundred and seventh part of the Windows Presentation Foundation Fundamentals tutorial begins to examine the TreeView control. This control is used to display hierarchical data.

Adding Items from Code

As with any ItemsControl, you can manipulate the items in the Items collection with the Add, Remove, RemoveAt and Clear methods. If you add a new TreeViewItem object to the TreeView's Items collection, it appears as a new root-level node. If you add to a TreeViewItem's collection, you create a child of that item.

Let's make it possible to add new items using the text box and the button. We'll create code behind the window that responds to the button's Click event by creating a new item containing the text from the text box. We'll add it as a child of the selected item in the tree, or as a root item if there is no selection.

To begin, modify the XAML for the button to register the Click event.

<Button Grid.Row="1" Grid.Column="1" Click="Add_Click">Add</Button>

To determine the selected item in a tree view you can read the SelectedItem property. If this is null, there is no selection. We'll use this knowledge with an if statement to determine whether to add a root item or a child. Add the following method to the code behind the window:

private void Add_Click(object sender, RoutedEventArgs e)
{
    var selected = Tree.SelectedItem as TreeViewItem;

    if (selected != null)
    {
        selected.Items.Add(new TreeViewItem { Header = NewItemInput.Text });
    }
    else
    {
        Tree.Items.Add(new TreeViewItem { Header = NewItemInput.Text });
    }

    NewItemInput.Clear();
}

Run the program and add several items to see the results.

Expanding and Collapsing Items

As you have seen, the user can expand and collapse items in the tree view using the arrow glyphs to the side of the parent item. You can also expand and collapse items programmatically. Each TreeViewItem includes an IsExpanded property. This returns a Boolean value, which is true when the item is expanded and false when its children are hidden. Changing the property updates the user interface.

Normally, when you select an item by clicking its content, rather than the arrows, it does not expand automatically. Let's add automatic expansion using the IsExpanded property. Start by modifying the TreeView's opening XAML tag to register the SelectedItemChanged event. This fires when the selection is changed.

<TreeView Name="Tree" Grid.ColumnSpan="2" Margin="0 0 0 2"
          SelectedItemChanged="Tree_SelectedItemChanged">

Now add the code to expand the selected item. We'll use the SelectedItem property to find the selected node and cast the returned object to a TreeViewItem. We can then access the IsExpanded property:

private void Tree_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
{
    var selected = Tree.SelectedItem as TreeViewItem;

    if (selected != null)
    {
        selected.IsExpanded = true;
    }
}

Run the program and click on the text part of one of the root nodes. As the item is selected, it expands automatically.

Expanding a Subtree

Another method of programmatically expanding items in a tree view is to expand an entire subtree. Calling a TreeViewItem's ExpandSubtree method ensures that its children, grandchildren and all other descendants are visible.

To demonstrate, update the code for the SelectedItemChanged event, as follows:

private void Tree_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
{
    var selected = Tree.SelectedItem as TreeViewItem;

    if (selected != null)
    {
        selected.ExpandSubtree();
    }
}

Try running the program. The normal expansion via the arrows remains unchanged. However, clicking the text of a node fully expands it. You can see this by selecting the IT node. The node and all of its children will be expanded.

Expanded and Collapsed Events

The TreeViewItem class defines two events, Expanded and Collapsed, which are raised when the item is expanded or collapsed, either by user action or programmatically. You can use these events to detect the change and react accordingly.

To demonstrate, let's listen for both events on the "Admin" tree view item. Register the events by modifying the appropriate TreeViewItem's opening XAML tag, as follows:

<TreeViewItem Header="Admin" Expanded="TreeViewItem_Expanded"
              Collapsed="TreeViewItem_Collapsed">

There are many things that you might wish to do in response to a node being opened or closed. We'll just show a message. Add the following code behind the window:

private void TreeViewItem_Expanded(object sender, RoutedEventArgs e)
{
    var expanded = sender as TreeViewItem;
    var message = string.Format("Expanded to show {0} items", expanded.Items.Count);
    MessageBox.Show(message);
}

private void TreeViewItem_Collapsed(object sender, RoutedEventArgs e)
{
    var collapsed = sender as TreeViewItem;
    var message = string.Format("Collapsed to hide {0} items", collapsed.Items.Count);
    MessageBox.Show(message);
}

If you run the program and expand or collapse the Admin node, you will see a message box that shows the number of child items present beneath Admin.

27 October 2014