C# Tree View With Multi-Type Binding

C# Tree View With Multi-Type Binding

I had an interesting problem where I need the leaves of the tree view to be different types, so in my tree view I have the following classes;

  • Family
  • Parent
  • Child
  • Pet

however notice that the Pet and Child classes are at the same level i.e. the leaf level.

Tree View

Classes

Here are my classes

Family

C#

Parent

C#

Child

C#

Pet

C#

View Model Base

C#

Family View Model

To create the data model we will create a View Model for the family and initialize the families observable collection.

C#

Children And Pets Converter

To make this work we want to create a multi value converter that can take in an array of all objects below the parent and combine them into a single observable collection, this is what this converter does.

C#

Tree View Xaml

First thing we need to define a root node in Xaml terms its a header

C#

Next we will bind the Tree View to the Families observable collection in the View Model.

C#

The Families observable collection contains a Family Class Which Contains a Parents Class and a Name Attribute for the Family Name.

C#

in the previous code block we set the item source, in this case we don’t know which item source to bind to since we have children and pets, so in this case we cant.

C#

This is where the converter comes in, we pass both collections into the converter as a multi-binding to create a singular collection.

C#

Lastly we have to define two data templates so that we can bind to the correct attributes

C#

I Changed the attribute names for the Pet and Child class and as a result we have to change the names in the two data templates as shown below.

C#

Completed Code.

C#