Wobbles
Wobbles

Reputation: 3135

using HierarchicalDataTemplate with different nested types

There seems to be a ton of information on HierarchicalDataTemplate, but I have had a hard time finding info specific enough to help me out with hierarchies containing different types.

Assuming the following class structure:

public class classA
{
    public string name{get;set;}
}
public class classB
{
    public string name{get;set;}
    public List<classA> subItems{get;set;}
}
public class classC
{
    public string name{get;set;}
    public List<classB> subItems{get;set;}
}

Now taking into assumption the reason the classes aren't self referencing thus keeping one type throughout my hierarchy is that there are fundamental differences in properties contained theirin, is there a way to create a type sensitive HierarchicalDataTemplate?

Upvotes: 2

Views: 3749

Answers (1)

Mark Feldman
Mark Feldman

Reputation: 16148

HierarchicalDataTemplate has a DataType property, so you use that to specify the type just as you do for DataTemplate. Let's say you wrap your hierarchy in a view model:

public class MyViewModel
{
    public List<classC> Items { get; set; }
}

And then create your hierarchy like so:

this.DataContext = new MyViewModel
{
    Items = new List<classC>
    {
        new classC
        {
            name = "Class C",
            subItems = new List<classB> {
                new classB{
                    name = "Class B1",
                    subItems = new List<classA>{
                        new classA {name="Class A1a"},
                        new classA {name="Class A1b"},
                        new classA {name="Class A1c"},
                    }
                },
                new classB{
                    name = "Class B2",
                    subItems = new List<classA>{
                        new classA {name="Class A2a"},
                        new classA {name="Class A2b"},
                        new classA {name="Class A2c"},
                    }
                }
            }
        }
    }
};

Then in XAML all you need to do is add the relevant DataTemplates and HierarchicalDataTemplates to your TreeView's resources block:

<TreeView ItemsSource="{Binding Items}">
    <TreeView.Resources>

        <DataTemplate DataType="{x:Type local:classA}" >
            <TextBlock Text="{Binding name}" Foreground="Blue" />
        </DataTemplate>

        <HierarchicalDataTemplate DataType="{x:Type local:classB}" ItemsSource="{Binding subItems}" >
            <TextBlock Text="{Binding name}" Foreground="Green" />
        </HierarchicalDataTemplate>

        <HierarchicalDataTemplate DataType="{x:Type local:classC}" ItemsSource="{Binding subItems}" >
            <TextBlock Text="{Binding name}" Foreground="Red" />
        </HierarchicalDataTemplate>

    </TreeView.Resources>
</TreeView>

Result:

enter image description here

Upvotes: 10

Related Questions