WPF C# TreeView of object with a 属性 Dictionary of List

WPF C# TreeView of object with a property Dictionary of List

我正在尝试创建一个可编辑的 TreeView 列表:

    public class CollectionType
    {
        public string Name {get; set;}

        public Dictionary<string, List<Size>> SizeGuide { get; set; }
    }

    public class Size
    {
        public string Name { get; set; }

        public string Weight { get; set; }
    }

这是我到目前为止的想法:

<TreeView Name="CollectionTypesSizes">
           <TreeView.Resources>
               <HierarchicalDataTemplate DataType="{x:Type self:CollectionType}" ItemsSource="{Binding SizeGuide}">
                   <StackPanel Orientation="Horizontal">
                       <TreeViewItem>
                           <TreeViewItem.Header>
                               <StackPanel Orientation="Horizontal">
                                   <TextBlock Text="{Binding Path=Name}"/>
                                   <TextBlock Text=": "/>
                                   <TextBlock Text="{Binding Path=SizeGuide.Count}" Foreground="CadetBlue"/>
                               </StackPanel>
                           </TreeViewItem.Header>                            
                       </TreeViewItem>
                   </StackPanel>
               </HierarchicalDataTemplate>                
           </TreeView.Resources>
       </TreeView>

但我不知道如何深入到 Size 对象以正确显示它:

TreeView result

我之前尝试过不同的方法,但在尝试使其可编辑时变得很复杂。

您可以制作嵌套的 HierarchicalDataTemplates:

<HierarchicalDataTemplate DataType="{x:Type local:CollectionType}" 
                          ItemsSource="{Binding SizeGuide}">

    <StackPanel Orientation="Horizontal">
        <TextBlock Text="{Binding Path=Name}"/>
        <TextBlock Text=": "/>
        <TextBlock Text="{Binding Path=SizeGuide.Count}" Foreground="CadetBlue"/>
    </StackPanel>

    <HierarchicalDataTemplate.ItemTemplate>
        <!--template for KeyValuePair<string, List<Size>> -->
        <HierarchicalDataTemplate ItemsSource="{Binding Path=Value}">
            <TextBlock Text="{Binding Path=Key}"/>

            <HierarchicalDataTemplate.ItemTemplate>
                <DataTemplate DataType="{x:Type local:Size}">
                    <StackPanel Orientation="Horizontal">
                        <TextBox Width="50" Text="{Binding Path=Name}"/>
                        <TextBlock Text=": "/>
                        <TextBox Width="50"  Text="{Binding Path=Weight}"/>
                    </StackPanel>
                </DataTemplate>
            </HierarchicalDataTemplate.ItemTemplate>
        </HierarchicalDataTemplate>
    </HierarchicalDataTemplate.ItemTemplate>

</HierarchicalDataTemplate>