Multiple templates for different types
In the next example, we have taken a slightly more complex case, where we want to show the tree of families and their members. The family should be represented in one way, while each of its members should be shown in another way. We achieved this by creating two different templates and specifying them as the source of the tree (or window or application - which is really up to you) and then, allowing the tree view to select the appropriate template based on the type of data underlying it.
.Xaml file
Ā
Ā
.cs File
Ā
public MainWindow()
{
InitializeComponent();
List families = new List();
MyFamily familyone = new MyFamily() { Name = "The Doe's" };
familyone.Members.Add(new FamilyMember() { Name = "John Doe", Age = 42 });
familyone.Members.Add(new FamilyMember() { Name = "Jane Doe", Age = 39 });
familyone.Members.Add(new FamilyMember() { Name = "Sammy Doe", Age = 13 });
families.Add(familyone);
MyFamily familyTwo = new MyFamily() { Name = "The Moe's" };
familyTwo.Members.Add(new FamilyMember() { Name = "Mark Moe", Age = 31 });
familyTwo.Members.Add(new FamilyMember() { Name = "Norma Moe", Age = 28 });
familyTwo.Add(familyTwo);
manyFamilies.ItemsSource = families;
}
public class MyFamily
{
public MyFamily()
{
this.Members = new ObservableCollection();
}
public string Name { get; set; }
public ObservableCollection Members { get; set; }
}
public class FamilyMember
{
public string Name { get; set; }
public int Age { get; set; }
}
Output
As mentioned, two templates have been revealed as part of TreeView resources, allowing TreeView to select the appropriate template based on the type of data to be displayed. A specified sample for a MyFamily type is a hierarchical sample, in which the property of the members is used to show its MyFamily members.
The template defined for the MyFamily Member type is a regular data template, as there are no child members in this type. However, if we wanted each family member to have a collection of their children and possibly their children, we could use a hierarchical template instead.
In both samples, we used an image representing a family or family members, and then we show some interesting data about it, such as the number of family members or the age of the person.
In Code-Bank, we simply create two family patterns, fill each of them with a set of members, and then add each of the family to the list, which is then used as a source of items for the tree view.