Click here to Skip to main content
15,884,388 members
Articles / Desktop Programming / WPF

WPF TreeListView Control

Rate me:
Please Sign up or sign in to vote.
4.90/5 (71 votes)
23 Aug 2012Apache3 min read 443.4K   24.4K   203   91
This article describes the usage of custom WPF TreeListView control comparing with basic TreeView
Image 1

Introduction

This articles explores the problems of standard WPF TreeView controls and describes a better way to display hierarchical data using a custom TreeListView control.

Background of TreeView

Windows Forms TreeView has quite a limited functionality and provides no easy way to extend it. WPF TreeView seems like a major step forward, at first glance. But in real application the lack of features like multiselection or multicolumn view become apparent. Moreover, things that were quite easy to do in Windows Forms are now much more complex in WPF because there's no simple way to get the container item for your business object displayed in the TreeView. For example, if you need to expand the currently selected node you have to use ItemContainerGenerator as described here or use a special model just to support selection/expanding (see here).

Another weakness of the WPF TreeView is poor performance. It takes more the 10 seconds to expand a node containing 5000 subnodes! Even navigation becomes very slow — more than a second to just move a focus.

TreeListView

But there is an alternative way to display hierarchical data — use the ListView. The basic idea is the following:

  • For each tree node we create a row in the ListView.

  • The ListViewItem template contains a special control named RowExpander which allows you to expand/collapse a node and any number of additional controls to represent the data. Those controls are shifted to the right depending on the Node level.

  • When the TreeNode is expanded/collapsed we need to add/remove rows to/from the ListView

Using this approach we get all the benefits from ListView: multiselection, a possibility to display several columns, performance improvements comparing to TreeView, less memory usage because of virtualization support (it means that visual elements will be created only for the items currently displayed on the screen).

Model-View

WPF TreeView is supposed to be used with HierarchicalDataTemplate where you specify a property containing child items. It's quite simple, but requires you to provide such a property in your business objects, which means that you can't display the hierarchy of simple types, like String, in the TreeView. Additionally, I prefer to use another approach — use a special interface which describes hierarchical data:

C#
public interface ITreeModel
{
    /// 
    /// Get list of children of the specified parent
    /// 
    IEnumerable GetChildren(object parent);

    /// 
    /// returns weather specified parent has any children or not.
    /// 
    bool HasChildren(object parent);
}

The HasChildren method is used to display/hide the expander control without calling GetChildren, which can be time expensive. Note that items are loaded on demand in TreeListView, which means the GetChildren method will be called only when the corresponding parent node expands.

Realization Details

We create subclasses of ListView and ListviewItem:

C#
public class TreeList: ListView
{
    /// 
    /// Internal collection of rows representing visible nodes, actually displayed
    /// in the ListView
    /// 
    internal ObservableCollectionAdv Rows
    {
        get;
        private set;
    } 

    protected override DependencyObject GetContainerForItemOverride()
    {
        return new TreeListItem();
    }

    protected override bool IsItemItsOwnContainerOverride(object item)
    {
        return item is TreeListItem;
    }
}

When the Aaren node is collapsed/expanded we need to insert/remove all child nodes and notify ListView about that. As the system class ObservableCollection doesn't provide methods for that we need to create our own collection class:

C#
public class ObservableCollectionAdv : ObservableCollection
{
    public void RemoveRange(int index, int count)
    {
        this.CheckReentrancy();
        var items = this.Items as List;
        items.RemoveRange(index, count);
        OnReset();
    }

    public void InsertRange(int index, IEnumerable collection)
    {
        this.CheckReentrancy();
        var items = this.Items as List;
        items.InsertRange(index, collection);
        OnReset();
    }
}

For every item created by the model we create a TreeNode class which will store node status (IsSelected, IsExpanded) and track changes in the model if it provides such information:

C#
void ChildrenChanged(object sender, NotifyCollectionChangedEventArgs e)
{
    switch (e.Action)
    {
    case NotifyCollectionChangedAction.Add:
        if (e.NewItems != null)
        {
            int index = e.NewStartingIndex;
            int rowIndex = Tree.Rows.IndexOf(this);
            foreach (object obj in e.NewItems)
            {
                Tree.InsertNewNode(this, obj, rowIndex, index);
                index++;
            }
        }
        break;

    case NotifyCollectionChangedAction.Remove:
        if (Children.Count > e.OldStartingIndex)
            RemoveChildAt(e.OldStartingIndex);
        break;

    case NotifyCollectionChangedAction.Move:
    case NotifyCollectionChangedAction.Replace:
    case NotifyCollectionChangedAction.Reset:
        while (Children.Count > 0)
            RemoveChildAt(0);
        Tree.CreateChildrenNodes(this);
        break;
    }
    HasChildren = Children.Count > 0;
    OnPropertyChanged("IsExpandable");
}

Using the Code

The source code of the article contains two examples using TreeListView. One uses a classic TreeView style and the other displays how to interact with the TreeListView. The other shows how several columns can be used to display system registry.

Points of Interest

In the current implementation of the TreeListView you have to keep the XAML markup of the TreeListItem in the client library. Which means that you have to copy it to each project using the control. Normally this information should be stored in the same library as the control itself, but it just didn't work this way. If somebody finds the way how to achieve this, don't hesitate to share it.

License

This article, along with any associated source code and files, is licensed under The Apache License, Version 2.0


Written By
Software Developer
Russian Federation Russian Federation
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
Generala couple of bugs (with fixes!) Pin
Yellowseed6-May-10 5:25
Yellowseed6-May-10 5:25 
GeneralRe: a couple of bugs (with fixes!) Pin
Member 866370412-Apr-12 21:45
Member 866370412-Apr-12 21:45 
GeneralNode Position Pin
Harvester of Sorrow23-Dec-09 1:56
Harvester of Sorrow23-Dec-09 1:56 
GeneralMultilevel Grid with column header Pin
Vaishnavi Karthik1-Dec-09 0:02
Vaishnavi Karthik1-Dec-09 0:02 
Question!Node adding BUG! Pin
tskrjd218-Nov-09 0:31
tskrjd218-Nov-09 0:31 
GeneralColumn resize bug Pin
daniel radford3-Nov-09 1:31
daniel radford3-Nov-09 1:31 
QuestionHow to use DataTemplateSelector with this TreeListView? Pin
Member 414098411-Aug-09 11:19
Member 414098411-Aug-09 11:19 
GeneralDeleting nodes Pin
Erik Vullings30-Jul-09 5:13
Erik Vullings30-Jul-09 5:13 
Great example, and I'm using it to display an XML file.

However, what's the best way to delete a treenode? Especially considering that it may or may not be expanded, and I want it to automatically delete all children too.
Any help is appreciated!

Cheers
Erik

Author of SubtitleCreator

QuestionProblem finding out whether an Item is expanded or not. Pin
FD_FTS23-Jul-09 23:35
FD_FTS23-Jul-09 23:35 
Generalonly parent is shown, no children... Pin
ub3rst4r8-Jul-09 16:40
ub3rst4r8-Jul-09 16:40 
GeneralRe: only parent is shown, no children... Pin
ub3rst4r11-Jul-09 14:52
ub3rst4r11-Jul-09 14:52 
AnswerRe: only parent is shown, no children... Pin
ub3rst4r14-Jul-09 17:31
ub3rst4r14-Jul-09 17:31 
QuestionCombobox inside cells - selected value? Pin
to_samGmbH25-Jun-09 4:45
to_samGmbH25-Jun-09 4:45 
QuestionHow to bind a sample xml file data to this TreeListView Pin
Member 24829683-Jun-09 7:47
Member 24829683-Jun-09 7:47 
GeneralVery efficient internals - however, it doesn't support true tree structure - missing users root node Pin
rzuffante8-Feb-09 3:53
rzuffante8-Feb-09 3:53 
GeneralLazy Loading Pin
bushRA7831-Dec-08 23:48
bushRA7831-Dec-08 23:48 
QuestionNice one... Have tryed to migrate it to SilverLight with no success... Pin
Berch30-Nov-08 5:16
Berch30-Nov-08 5:16 
QuestionHow sort subnodes by field when press on column header? Pin
time-best28-Nov-08 2:16
time-best28-Nov-08 2:16 
GeneralBinding Pin
Michael Sync27-Nov-08 23:02
Michael Sync27-Nov-08 23:02 
AnswerRe: Binding Pin
time-best28-Nov-08 2:09
time-best28-Nov-08 2:09 
Generalexpand column to largest item Pin
Leblanc Meneses20-Nov-08 7:50
Leblanc Meneses20-Nov-08 7:50 
Questionhow to add a Edit-cell feature? Pin
Frank Thielemann10-Nov-08 4:41
Frank Thielemann10-Nov-08 4:41 
AnswerRe: how to add a Edit-cell feature? Pin
Andrey Gliznetsov11-Nov-08 4:43
Andrey Gliznetsov11-Nov-08 4:43 
GeneralNice, but... Pin
Michal Brylka5-Nov-08 23:33
Michal Brylka5-Nov-08 23:33 
GeneralRe: Nice, but... Pin
FD_FTS23-Jul-09 23:38
FD_FTS23-Jul-09 23:38 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.