WPF Treeview: data binding of heterogeneous types of data using CompositeCollection class

27 Sep

Data binding plays crucial roles in WPF, and is one of the most elegant advantages of using MVVM design pattern.

For the WPF TreeView control, one can use HierarchicalDataTemplate to easily bind homogeneous data structures as shown below. Several good blogs had covered such topics, for instance,  David Sackstein’s blogClaus Konrad Blog, to list a few.


When we want to bind heterogeneous data types, i.e. the sub items contain more than one types of data (e.g. both the folders and files) to the TreeView, we need some extra efforts.


I have been struggling on this for quite a few days, and after searching StackOverflow and other MSDN blogs, finally I found one solution: use CompositeCollection. Below is my implementation to present all the subfolders and files inside a TreeView control.

  • Create a class called FolderItem, and add constructors and data member as follows:


Add another property called children, which contains both the FolderItem and FileInfo types of objects. Here the CompositeCollection is used to hold heterogeneous types of data collection.


Once the model is defined as above, we can then use DataTemplate and HierarchicalDataTemplate in XAML:image

The correct use of DataTemplate or HierarchicalDataTemplate is the key. Whenever there is recursion, the HierarchicalDataTemplate should be used. In our case, the FolderItem contains sub-FolderItem + FileInfo objects, so for FolderItem,  HierarchicalDataTemplate is used. For the FileInfo objects, there is no child associated with each FileIno, therefore DataTemplate is used instead.

To properly understand the rationale of HierarchicalDataTemplate, I found this blog from StackOverflow is very helpful.

Finally, in the window’s Loaded event handler, add below code:


Rebuild and run. Enjoy!

1 Comment

Posted by on September 27, 2012 in General


One response to “WPF Treeview: data binding of heterogeneous types of data using CompositeCollection class

  1. Ivan

    September 19, 2015 at 2:13 pm

    I’ve tried implementing your solution in a TreeView control using FTP to get the items. But as soon as I open the first level it seems to list the next level but also loads the third level of items. Is there something that I’m not seeing, maybe some kind of a preloader in TreeView?
    I would really like to stop ‘preloading’ the third sublevel of folders, because on FTP it can get real slow.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: