Adding Items from Code

As with any ItemsControl, you can manipulate the items in the Items collection with the Add, Remove, RemoveAt and Clearmethods. 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 Clickevent 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:

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.

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:

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: