Create a data object and bind it to the itemsource of the Treeview

Data Object
Let us create a class called Person with Name, Age and Children as properties.

public class Person
    {
        public Person()
        {
            Children = new ObservableCollection<Person>();
        }
        public string Name { get; set; }
        public int Age { get; set; }
        public ObservableCollection<Person> Children { get; set; }
    }

Treeview template

<TreeView Name="trVwPerson" xmlns:obj="clr-namespace:TestWpf">
  <TreeView.ItemTemplate>
     <HierarchicalDataTemplate DataType = "{x:Type obj:Person}" ItemsSource="{Binding Path=Children}">
         <StackPanel Orientation="Horizontal">
             <TextBlock Text="{Binding Path=Name}"/>
             <TextBlock Width="10"/>
             <TextBlock Text="{Binding Path=Age}"/>
         </StackPanel>
      </HierarchicalDataTemplate>
   </TreeView.ItemTemplate>
</TreeView>

Item Source Binding
After creating the class and using the template, we need to bind the item source of the Treeview to a list.

ObservableCollection<Person> Souce = new ObservableCollection<Person>();
            Person P1 =
            new Person()
            {
                Name = "GrandFather",
                Age = 90
            };
            Person P11 = new Person()
            {
                Name = "Father1",
                Age = 60
            };
            Person P111 = new Person()
            {
                Name = "Child1",
                Age = 30
            };
            P11.Children.Add(P111);
            Person P12 = new Person()
            {
                Name = "Father2",
                Age = 60
            };
 
            P1.Children.Add(P11);
            P1.Children.Add(P12);
 
            Person P2 =
            new Person()
            {
                Name = "GrandFather2",
                Age = 91
            };
            Person P3 =
            new Person()
            {
                Name = "GrandFather3",
                Age = 92
            };
            Souce.Add(P1);
            Souce.Add(P2);
            Souce.Add(P3);
            trVwPerson.ItemsSource = Souce;

Enjoyed this post? Share it!

 

Leave a comment

Your email address will not be published.