Two Lists as children in a WPF TreeView

958 Views Asked by At

I have a WPF TreeView that is bound to a list of objects that has several lists in each of them.

public List<OwnerClass> OwnerClasses {get; set;}

public class OwnerClass
{
    public List<SomeObject> SomeObjects { get; set; }
    public List<OtherObject> OtherObjects { get; set; }
}

I am looking to find a way to show both lists as children of the parent.

Like this:

> Owner1
   |
   + SomeObject 1
   + SomeObject 2
   + SomeObject 3
   + OtherObject 1
   + OtherObject 2
   + OtherObject 3
   + OtherObject 4

> Owner2
   |
   + SomeObject 1
   + SomeObject 2
   + SomeObject 3
   + OtherObject 1
   + OtherObject 2
   + OtherObject 3
   + OtherObject 4

I want the treeview functionallity, but I want the child lists side by side. (And each one as a tree view, because they in turn have lists.)

Is this possible?

2

There are 2 best solutions below

0
On

You need two things really to do this easily. The first has been demonstrated nicely by @DLeh, although I'd recommend using the ObservableCollection<T> class rather than the List<T> class when using WPF.

The second thing you need is a HierarchicalDataTemplate. It's like an ordinary DataTemplate, but it allows you to set a source for the child nodes:

<HierarchicalDataTemplate DataType="{x:Type YourXmlNamespacePrefix:OwnerClass}" 
    ItemsSource="{Binding AllObjects}">
    <TextBlock Text="{Binding SomePropertyFromObject}"/>
</HierarchicalDataTemplate>

You can find out more from the HierarchicalDataTemplate Class page on MSDN.

0
On

You could probably make a property that "joins" the two lists into one:

public class OwnerClass
{
    public List<SomeObject> SomeObjects { get; set; }
    public List<OtherObject> OtherObjects { get; set; }
    public object AllObjects 
    {
        get
        {
            List<object> list = SomeObjects;
            list.AddRange(OtherObjects);
            return list;
        }
    }
}