Saturday, February 08, 2014

TreeListView: Show Hierarchy Data with Details in Columns

This is the first session of this topic. I'll introduce the minimum steps needed to build a TreeListView. The TreeListView is able to present hierarchy data with details in columns. See the following diagram:

Inline image 1

The main Avalon elements we are going to cover in this session are TreeView, TreeViewItem, GridViewColumnCollection, GridViewRowPresenter, GridViewHeaderRowPresenter and Binding of course.

 

Step 1. Sub-class TreeView and TreeViewItem

The key in this step is to override proper methods to make sure correct container is generated.

public class TreeListView : TreeView
{
    protected override DependencyObject GetContainerForItemOverride(object item)
    {
        return new TreeListViewItem();
    }
    protected override bool IsItemItsOwnContainerOverride(object item)
    {
        return item is TreeListViewItem;
    }
    public GridViewColumnCollection Columns
    {
        get
        {
            if (_columns == null)
            {
                _columns = new GridViewColumnCollection();
            }
            return _columns;
        }
    }
    private GridViewColumnCollection _columns;
}
 
public class TreeListViewItem : TreeViewItem
{
    // copy the above two overrides here, they are same.
}
 

Step 2. Add a Level property to TreeListViewItem

Make the item be aware of the level it belongs to.

public class TreeListViewItem : TreeViewItem
{
    public int Level {
        get {
            if (_level == -1) {
                TreeListViewItem parent = ItemsControl.ItemsControlFromItemContainer(this) as TreeListViewItem;
                _level = (parent != null) ? parent.Level + 1 : 0;
            }
            return _level;
        }
}
}
 

Step 3. Write a data template for the 1st column

Read more: MSDN