Live Chat Icon For mobile
Live Chat Icon

How do I bind my tree to a hierarchical list?

Platform: WPF| Category: TreeView

Let us say you have a hierarchical list like this:


- Division1
|
|--- Department1
|   |--- Room1
|   |--- Room2
|--- Department2
|   |--- Room3
|   |--- Room4
- Division2
(......) 

With corresponding types like this:

[C#]
public class Division
{

public string Name{...}

public DepartmentsCollection Departments{...}

}

public class Department
{

public string Name{...}

public RoomsCollection Rooms{...}

}

public class Room
{
public string Name{....}
}

You could then bind a collection of Divisions to a tree to achieve the above look and feel by defining a HierarchicalDataTemplate for Division and Department and a DataTemplate for Room types, as follows:

[XAML]
<HierarchicalDataTemplate DataType='{x:Type src:Division}' ItemsSource='{Binding Path=Departments}'>   
  
<TextBlock Text='{Binding Path=Name}'/>   
  
</HierarchicalDataTemplate>  

<HierarchicalDataTemplate DataType='{x:Type src:Department}' ItemsSource='{Binding Path=Rooms}'>   
  
<TextBlock Text='{Binding Path=Name}'/>   
  
</HierarchicalDataTemplate>  

<DataTemplate DataType='{x:Type src:Room}'>   
  
<TextBlock Text='{Binding Path=Name}'/>   
  
</DataTemplate>  

You can then bind the TreeView to a collection of Divisions.

[XAML]
<!--myDivisonsCollection could be an ObjectDataSource returning the list of Divisions collection --!>
<TreeView ItemsSource='{Binding Source={StaticResource myDivisionsCollection}}'></TreeView>

Share with