Simple WPF TreeView Control Programmatically

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:

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

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. That will 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:

  
  1. TreeViewItem ParentItem = new TreeViewItem();  
  2. ParentItem.Header = "Parent";  
  3. TreeView1.Items.Add(ParentItem);  
  4. //  
  5. TreeViewItem Child1Item = new TreeViewItem();  
  6. Child1Item.Header = "Child One";  
  7. ParentItem.Items.Add(Child1Item);  
  8. //  
  9. TreeViewItem Child2Item = new TreeViewItem();  
  10. Child2Item.Header = "Child Two";  
  11. ParentItem.Items.Add(Child2Item);  
  12. TreeViewItem SubChild1Item = new TreeViewItem();  
  13. SubChild1Item.Header = "Sub Child One";  
  14. Child2Item.Items.Add(SubChild1Item);  
  15. TreeViewItem SubChild2Item = new TreeViewItem();  
  16. SubChild2Item.Header = "Sub Child Two";  
  17. Child2Item.Items.Add(SubChild2Item);  
  18. TreeViewItem SubChild3Item = new TreeViewItem();  
  19. SubChild3Item.Header = "Sub Child Three";  
  20. Child2Item.Items.Add(SubChild3Item);  
  21. //  
  22. TreeViewItem Child3Item = new TreeViewItem();  
  23. Child3Item.Header = "Child Three";  
  24. ParentItem.Items.Add(Child3Item);  
The following is the tree created by the preceding code: