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"/>
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:
- 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);

Sibeesh VenuPosted Dec 31, 2015, 3:20 AM
Nice Share
Santhakumar MunuswamyPosted Dec 31, 2015, 1:52 AM
Thanks for nice article
Kiranteja JallepalliPosted Dec 30, 2015, 10:47 PM
Nice Share
Raja TPosted Dec 30, 2015, 9:56 PM
Nice Sir, thanks for sharing