using HierarchicalDataTemplate with different nested types

久未见 提交于 2021-02-08 05:22:25

问题


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?


回答1:


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:



来源:https://stackoverflow.com/questions/35564985/using-hierarchicaldatatemplate-with-different-nested-types

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!