Live Chat Icon For mobile
Live Chat Icon

I have a custom type called Group which has 2 collections Products and Services and I want both these collections to appear as siblings when the Groups collection is bound to a tree, how do I do that?

Platform: WPF| Category: TreeView

Let us say you want have a hierarchical list like this:


- Group
|
|--- Products
|   |--- Product1
|   |--- Product2
|--- Service
|   |--- Service1
|   |--- Service2

And the underlying Group type defined like this:


public class Group
{

public string Name{...}

public ProductCollection Products{...}

public ServiceCollection Services{...}

}

Then you will have trouble binding this to a TreeView to get the above indicated effect. To achieve the above effect, you should first implement a dummy ‘Children’ collection that is a combination of the Products and Services collection as follows:


public class Group
{

public string Name{...}

public ProductCollection Products{...}

public ServiceCollection Services{...}

public IList Children{/*Combine Products and Services and return the list here. This could be just a read-only list.*/}

}

Then create a HierarchicalDataTemplate for the Group object as follows:

[XAML]
<HierarchicalDataTemplate DataType='{x:Type src:Group}' ItemsSource='{Binding Path=Children}'>   
  
<TextBlock Text='{Binding Path=Name}'/>   
  
</HierarchicalDataTemplate>  

This will render both the Products and Services list as siblings at the same level.

You should also declare HierarchicalDataTemplates for the Product and Service types you might have defined.

You would of course, bind the tree to a collection of Group items.

Share with

Share on twitter
Share on facebook
Share on linkedin

Related FAQs

Couldn't find the FAQs you're looking for?

Please submit your question and answer.