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";
TreeViewItem Child1Item = new TreeViewItem();
Child1Item.Header = "Child One";
TreeViewItem Child2Item = new TreeViewItem();
Child2Item.Header = "Child Two";
TreeViewItem SubChild1Item = new TreeViewItem();
SubChild1Item.Header = "Sub Child One";
TreeViewItem SubChild2Item = new TreeViewItem();
SubChild2Item.Header = "Sub Child Two";
TreeViewItem SubChild3Item = new TreeViewItem();
SubChild3Item.Header = "Sub Child Three";
TreeViewItem Child3Item = new TreeViewItem();
Child3Item.Header = "Child Three";

The following is the tree created by the preceding code: