Thought I will start with the control that gave me many sleepless nights, WPF Tree view. When I started off with WPF I needed to show a recursive object in a tree view and frankly had night mares doing so but in the end it turned out pretty simple. So let’s consider a class as shown below
public class Person
{
string _Name;
int _Age;
List _Children;
public Person()
{
_Children = new List();
}
public string Name
{
get
{
return _Name;
}
set
{
_Name = value;
}
}
public int Age
{
get
{
return _Age;
}
set
{
_Age = value;
}
}
public List Children
{
get
{
return _Children;
}
}
}
So as u can see the no: of levels can be determined at runtime only.Now what we will do is let WPF do all the hard work and find out how many levels there are while we sit back and enjoy the show.To do this we use the tree view with the template shown below –
<TreeView Name="trVwPerson">
<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>
Here we are using a Hierarchial Data template and sets it’s data type
as the class we have declared earlier, so when we set the item source of the tree , it will automatically pick this template for an object of type Person and apply it as the item template.
To bind the item source I’ just create a junk list of the said class and set it to the item source of the tree view.
List Souce = new List();
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;
and there u have a hierarchial tree with n number of levels.