Bind RadTreeView to Self-Referencing Data
This tutorial will show you how to display a RadTreeView with flat, self-referencing data, loaded from a database, that has properties ID and ParentID (or similar) which define the hierarchy.
Consider the following very simple data object:
Example 1: Defining the DataItem class
Those data objects are added into a special DataItemCollection class, that inherits ObservableCollection
Example 2: Defining DataItemCollection
Normally when you load your data objects from a service in your application, you will have auto-generated partial classes, that are relatively easy to extend.
Now we are ready to data-bind our RadTreeView:
Example 3: Defining the resources
Example 4: Defining the RadTreeView
There is one non-standard thing: all ItemsSource bindings are made through a ValueConverter. This ValueConverter will create the "real" hierarchy for us:
Example 5: Defining the HierarchyConverter
When a DataItem object is passed as value, we are binding a TreeViewItem, so the Convert() method will return all DataItem objects from the Owner collection that have ParentID equal to the ID of the passed DataItem. When a DataItemCollection is passed, we are binding the RadTreeView, so the Convert() method will return the root-level DataItem objects, that have ParentID=0. Of course, it is up to you to decide whether you want a single, or separate converters for both of the cases. It is done in this way for simplicity, but if you want, you could split the code into two classes.
Example 6: Populating the RadTreeView
Image 1: Self-Referencing RadTreeView
You can check out this example in the RadTreeView SDK examples or in the SDK Samples Browser that provides a more convenient approach in exploring and executing the examples in the Telerik XAML SDK repository. The SDK Samples Browser application is available for download from this link.