Bind RadTreeView to Hierarchical Data and Use Style Binding
This tutorial demonstrates the usage of HierarchicalDataTemplate and Style Bindings in RadTreeView.
For more information about HierarchicalDataTemplate take a look at the HierarchicalDataTemplates topic.
Imagine the following scenario. You have an Organization that has several Departments, and each Department has several Employees.
It is not that difficult to create a data source reflecting the above structure. This is how the three classes look like:
-
Person class:
-
Department class:
-
Organization class
As you can see, an Organization has a Name and a list of Departments. A Department also has a Name, as well as a list of people that work in that Department. A Person has a Name. There are two more properties - Selected and Expanded. They will be explained further in the article, but in short, they will be used to control whether a certain RadTreeViewItem is expanded or selected.
Having the above three classes set up, it is time to create and populate a data source, which will be passed to the RadTreeView's ItemsSource property.
And setting RadTreeView's ItemsSource property in XAML:
Now it is time to define how each level of the RadTreeView will look like. You should use HierarchicalDataTemplate.
But what if you want to expand only the "Silverlight" node and to select the "John" node, leaving the WPF node collapsed. This is where the Style Binding comes in hand.
Define a new style with RadTreeViewItem for target type.
Find your treeview declaration and set the ItemContainerStyle property.
As you can see, the IsSelected property of each RadTreeViewItem is bound to the Selected property in the data source. The same is with the IsExpanded property. That's why now you have to update your data source.
So now, if you run the project, you will see the following result:
If you want to implement two way data binding, your business objects should implement the INotifyPropertyChanged interface. Additionally, you should set the Binding's Mode to TwoWay in the Style declaration.
<Style x:Key="ItemContainerStyle" TargetType="{x:Type telerik:RadTreeViewItem}">
<Setter Property="IsSelected" Value="{Binding Path=Selected, Mode=TwoWay}"/>
<Setter Property="IsExpanded" Value="{Binding Path=Expanded, Mode=TwoWay}"/>
</Style>