在 TreeView 中有 HierarchicalDataTemplates [英] Having HierarchicalDataTemplates in a TreeView

查看:13
本文介绍了在 TreeView 中有 HierarchicalDataTemplates的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

关于我之前在 (WPF:在 TreeViewItem 中正确存储对象)

是否可以在 TreeView 中嵌套 HierarchicalDataTemplate?

举个例子:

代码:

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:

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

从上面可以看出,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 控件会根据它需要的 DataType 来处理嵌套模板.因此,只需为专辑和艺术家类型定义两个 HierarchicalDataTemplates,并为您的 Track 类定义一个普通的 DataTemplate.

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.

   <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>

这篇关于在 TreeView 中有 HierarchicalDataTemplates的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆