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 blog, Claus 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.
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!