有HierarchicalDataTemplates在一个TreeViewHierarchicalDataTemplates、TreeView

2023-09-02 01:35:36 作者:未燃尽的烟

至于一个问题,我在前面贴(WPF:正确存储对象的树型视图)的

是否有可能已经在一个TreeView嵌套的 HierarchicalDataTemplate S'

Is it possible to have nested HierarchicalDataTemplates in a TreeView?

看看下面的例子:

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

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

正如你从上面看到,TreeView中只具有约束力的艺术家和他们的专辑。我怎么可以修改它也包括专辑的曲目(作为专辑的子列表IE)?

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控件将采取筑巢它基于它要求数据类型的照顾。因此,只要定义两个HierarchicalDataTemplates的专辑和艺术家的类型,一个普通的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>