C# 在 TreeView 中有 HierarchicalDataTemplates

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/719609/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 22:23:29  来源:igfitidea点击:

Having HierarchicalDataTemplates in a TreeView

c#.netwpfxamltreeview

提问by Andreas Grech

With regards to a question I posted earlier on (WPF: Correctly storing an object in a TreeViewItem)

关于我之前发布的一个问题(WPF:在 TreeViewItem 中正确存储对象

Is it possible to have nested HierarchicalDataTemplates in a TreeView?

是否可以HierarchicalDataTemplate在 TreeView 中嵌套s?



Take the following example:

以下面的例子为例:

Code:

代码:

public class Artist
{
        private readonly ICollection<Album> _children = new ObservableCollection<Album>();
        public string Name { get; set; }

        public ICollection<Album> Albums
        {
            get { return _children;}
        }
}

public class Album
{
        private readonly ICollection<Track> _children = new ObservableCollection<Track>();
        public string Name { get; set; }

        public ICollection<Track> Tracks
        {
            get { return _children;}
        }
}

Xaml:

Xml:

<TreeView x:Name="_treeView">
        <TreeView.Resources>
                <HierarchicalDataTemplate DataType="{x:Type local:Artist}" ItemsSource="{Binding Albums}">
                        <TextBlock Text="{Binding Name}"/>
                </HierarchicalDataTemplate>
        </TreeView.Resources>
</TreeView>

As you see from the above, the TreeView is only binding the Artists and their albums. How can I modify it to include also the Tracks of the albums (as a sub-list of the albums ie) ?

从上面可以看出,TreeView 只绑定了艺术家和他们的专辑。我如何修改它以包括专辑的曲目(作为专辑的子列表,即)?

采纳答案by Jobi Joy

You dont need a nested template here, since TreeView control will take care of nesting it based on the DataType it requires. So just define Two HierarchicalDataTemplates for Album and Artist Type and one ordinary DataTemplate for your Track class.

这里不需要嵌套模板,因为 TreeView 控件会根据它需要的 DataType 来处理嵌套模板。因此,只需为专辑和艺术家类型定义两个 HierarchicalDataTemplates,并为您的 Track 类定义一个普通的 DataTemplate。

   <HierarchicalDataTemplate  DataType="{x:Type local:Artist}" ItemsSource="{Binding Albums}" >          
         <TextBlock Text="{Binding Name}"/>                 
    </HierarchicalDataTemplate>
    <HierarchicalDataTemplate  DataType="{x:Type local:Album}" ItemsSource="{Binding Tracks}" >
        <TextBlock Text="{Binding Name}"/>
    </HierarchicalDataTemplate>        
    <DataTemplate DataType="{x:Type local:Track}">
        <TextBlock Text="{Binding Name}"/>
    </DataTemplate>