How do I bind a TreeView to a hierarchical list where some nodes have multiple child lists?

Platform: WPF| Category: TreeView

For example, if you have to bind to a hierarchical data source containing data like this:

Companies
    Company
       Departments
          Department
             Employees
                Employee
             Computers
                Computer

Where the Department type has 2 lists – Employees and Computers as follows:


namespace HierarchicalData.Classes
{
    public class Department
    {
        public string Name { get; set; }

        List _employees = new List();

        public List Employees
        {
            ...
        }
        List _computers = new List();

        public List Computers
        {
            ...
        }
    }
}

Then you will have to create templates as follows:


        <local:CompanyList x:Key='companies'/>

        <HierarchicalDataTemplate x:Key='EmployeeTemplate'>
            <TextBlock Text='{Binding Path=Name}' />
        </HierarchicalDataTemplate>

        <HierarchicalDataTemplate x:Key='ComputerTemplate'>
            <TextBlock Text='{Binding Path=Name}' />
        </HierarchicalDataTemplate>

        <HierarchicalDataTemplate x:Key='DepartmentTemplate'>
            <TreeViewItem Header='{Binding Path=Name}'>
                <TreeViewItem Header='Employees' ItemsSource='{Binding Path=Employees}'
                          ItemTemplate='{StaticResource EmployeeTemplate}'/> 
                <TreeViewItem Header='Computers' ItemsSource='{Binding Path=Computers}'
                          ItemTemplate='{StaticResource ComputerTemplate}'/>                
            </TreeViewItem>
        </HierarchicalDataTemplate>

        <HierarchicalDataTemplate x:Key='CompanyTemplate'
                    ItemsSource='{Binding Path=Departments}' 
                    ItemTemplate='{StaticResource DepartmentTemplate}'> 
            <TextBlock Text='{Binding Path=Name}' />
        </HierarchicalDataTemplate>

        <TreeView Name='_myTreeView' Margin='0,0,0,0' 
          ItemsSource='{Binding Source={StaticResource companies}}' 
          ItemTemplate='{StaticResource CompanyTemplate}'/>

Share with