Simple WPF TreeView Control Programmatically


Click here to change the theme.

This article provides a simple sample of populating a WPF TreeView Control programmatically. There are many samples of creating a WPF TreeView Control and populating it in XAML but in actual use we are much more likely to populate a TreeView Control dynamically from data. That must be done in code such as C#, not XAML.

Let us begin with the following in the XAML:

<TreeView x:Name="TreeView1" Margin="0,0,0,0"/>

You can download the sample code for dertails.

The TreeView Class has a member, "Items", that is an ItemCollection. For a TreeView an ItemCollection is a collection of TreeViewItem objects. TreeViewItem objects also have an "Items" member that is an ItemCollection. That creates a recursively hierarchical structure.

We need to add at least one TreeViewItem to the Items object of the TreeView Class to be the root node(s) of the TreeView. Typically there is only one node at the root but it is possible to have multiple root nodes. Then we add TreeViewItem objects to the relevant Items of TreeViewItem objects. The following code will create a simple tree:

TreeViewItem ParentItem = new TreeViewItem();
ParentItem.Header = "Parent";
TreeView1.Items.Add(ParentItem);
//
TreeViewItem Child1Item = new TreeViewItem();
Child1Item.Header = "Child One";
ParentItem.Items.Add(Child1Item);
//
TreeViewItem Child2Item = new TreeViewItem();
Child2Item.Header = "Child Two";
ParentItem.Items.Add(Child2Item);
TreeViewItem SubChild1Item = new TreeViewItem();
SubChild1Item.Header = "Sub Child One";
Child2Item.Items.Add(SubChild1Item);
TreeViewItem SubChild2Item = new TreeViewItem();
SubChild2Item.Header = "Sub Child Two";
Child2Item.Items.Add(SubChild2Item);
TreeViewItem SubChild3Item = new TreeViewItem();
SubChild3Item.Header = "Sub Child Three";
Child2Item.Items.Add(SubChild3Item);
//
TreeViewItem Child3Item = new TreeViewItem();
Child3Item.Header = "Child Three";
ParentItem.Items.Add(Child3Item);

The following is the tree created by the preceding code:

Tree