WPF Treeview Databinding Hierarchal Data with mixed types

Since you want the elements in the TreeView to have a list of children that consists of both Categories Products, you will want your Category ViewModel to have a collection that consists of both Categories and Products. For example, you could use a CompositeCollection to combine your existing collections:

public class Category
{
    public string Name { get; set; }
    public List<Category> Categories { get; set; }
    public List<Product> Products { get; set; }

    public IList Children
    {
        get
        {
            return new CompositeCollection()
            {
                new CollectionContainer() { Collection = Products },
                new CollectionContainer() { Collection = Categories }
            };
        }
    }
}

(In real code, you would probably want to keep a reference to the same collection object rather than creating a new one each time.)

Then in your HierarchicalDataTemplate, use the combined list as the ItemsSource:

<HierarchicalDataTemplate DataType="{x:Type src:Category}"
                          ItemsSource="{Binding Children}">

The items will be a mix of Product and Category objects, and WPF will use the appropriate DataTemplate for each one.

Leave a Comment