WPF TreeView - 组项目列表

时间:2016-09-20 10:39:04

标签: c# wpf xaml treeview

我有一个看起来像这样的类的列表:

class MyClass
{
   string Group {get;set;}
   string SubGroup {get;set;}
   string Item {get;set;}
}

在我的树视图中,我想将列表分组为:

组别1
... SubGroup1
......项目1
......第2项 ... SubGroup2
......项目3
... SubGroup3
......项目4
......项目5
第2组
... SubGroup4
......第6项

我的xaml应该是什么样的?

我已尝试使用嵌套的HierarchicalDataTemplates,GroupStyle和CollectionViewSource,但似乎没有任何效果......

此外,能够编辑Item属性会很高兴。

编辑:已经被称为Grouping child objects in WPF TreeView的副本,但似乎这个家伙开始时我想要最终得到(有点)

1 个答案:

答案 0 :(得分:0)

一个好的代码 - 撒玛利亚人写了这个。我会在这里发布,以防其他人发现它有用:

                                                                             

    <DataTemplate x:Key="LeafTemplate">
        <!--your item's property-->
        <TextBlock Text="{Binding Path=Val3}"/>
    </DataTemplate>

    <HierarchicalDataTemplate ItemsSource="{Binding Items}" x:Key="Level2GroupTemplate" ItemTemplate="{StaticResource LeafTemplate}">
        <!--GroupItem.Name-->
        <TextBlock Text="{Binding Path=Name}" />
    </HierarchicalDataTemplate>

    <HierarchicalDataTemplate ItemsSource="{Binding Items}" x:Key="Level1GroupTemplate"  ItemTemplate="{StaticResource Level2GroupTemplate}">
        <!--GroupItem.Name-->
        <TextBlock Text="{Binding Path=Name}" />
    </HierarchicalDataTemplate>

</Window.Resources>

    public ObservableCollection<TestTreeClass> TestTreeList
    {
        get { return (ObservableCollection<TestTreeClass>)GetValue(TestTreeListProperty); }
        set { SetValue(TestTreeListProperty, value); }
    }

    // Using a DependencyProperty as the backing store for TestTreeList.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty TestTreeListProperty =
        DependencyProperty.Register("TestTreeList", typeof(ObservableCollection<TestTreeClass>), typeof(MainWindow), new PropertyMetadata(null));

    TestTreeList = new ObservableCollection<TestTreeClass>()
        {
            new TestTreeClass() { Val1 = "AAA", Val2 = "111", Val3 = "abc" },
            new TestTreeClass() { Val1 = "AAA", Val2 = "111", Val3 = "def" },
            new TestTreeClass() { Val1 = "BBB", Val2 = "111", Val3 = "ghi" },
            new TestTreeClass() { Val1 = "BBB", Val2 = "111", Val3 = "jkl" },
            new TestTreeClass() { Val1 = "AAA", Val2 = "222", Val3 = "mno" }
};