In the previous posts I have shown how I used the Composite Pattern to describe hierarchical data, to use LINQ to XML to read such data from an XML file, and to present the data in a TreeView with the HierarchicalDataTemplate.
This post assembles the all pieces into a WPF application. You can find all the source code here.
The WPF application comprises two assemblies: OrganizationData and Organization View. OrganizationData defines the business objects and reads data from XML files. OrganizationView presents the data in a TreeView and demonstrates the data binding between the data and the TreeView.
In the Window I provide 3 buttons whose role is to modify the data in code so we can see the effect of databinding on the tree. Here is the code for each:
Button 1: Recruit Managers
void FindManagers(List<Composite> managers, Composite c)
{
if (c is Manager)
{
managers.Add(c);
}
if (c.Children != null)
{
foreach (Composite child in c.Children)
FindManagers(managers, child);
}
}
void Recruit<T>() where T : Employee, new()
{
List<Composite> managers = new List<Composite>();
FindManagers (managers, organization);
foreach (Manager m in managers)
{
m.Children.Add(new T
{
Name = m.Name + "_recruit",
Salary = m.Salary * 0.9,
Role = "Newbie"
}
);
}
}
private void RecruitManagers_Click(object sender, RoutedEventArgs e)
{
Recruit<Manager>();
}
Button 2: Recruit Employees
private void RecruitEmployees_Click(object sender, RoutedEventArgs e)
{
Recruit<Employee>();
}
Button 3: Increase Salaries
private void IncreaseSalary_Click(object sender, RoutedEventArgs e)
{
IncreaseSalary(organization);
}
void IncreaseSalary(Composite c)
{
if (c is Employee)
{
(c as Employee).Salary *= 1.2;
}
if (c.Children != null)
{
foreach (Composite child in c.Children)
{
IncreaseSalary(child);
}
}
}
Each of these operations changes the data and the results are propagated to the Window. Furthermore, each new object is styled according to its type.
This is what the Organization View looks like after I worked with the buttons a few times.

Summary
- The Composite Pattern is useful for representing hierarchical data.
- LINQ to XML makes it easy to read the information from file.
- The HierarchicalDataTemplate provides a simple way to define the styles of nodes at all levels of a tree depending on the type of the object associated with the node.