WPF TreeView控件中绑定嵌套的Dictionary>集合

需求是将Dictionary<string, Dictionary<string, string>>集合绑定到TreeView中展示。

        <TreeView x:Name="treeView" FontSize="16">
            <TreeView.ItemTemplate>
                <HierarchicalDataTemplate ItemsSource="{Binding Value}">
                    <TextBlock  Text="{Binding Key}"/>
                    <HierarchicalDataTemplate.ItemTemplate>
                        <HierarchicalDataTemplate ItemsSource="{Binding Value.Value}">
                            <StackPanel Orientation="Horizontal">
                                <TextBlock Text="{Binding Key}"/>
                                <TextBlock Text="{Binding Value}"/>
                            </StackPanel>
                        </HierarchicalDataTemplate>
                    </HierarchicalDataTemplate.ItemTemplate>
                </HierarchicalDataTemplate>
            </TreeView.ItemTemplate>
            
            <!--将节点默认展开-->
            <TreeView.ItemContainerStyle>
                <Style TargetType="{x:Type TreeViewItem}">
                    <Setter Property="IsExpanded" Value="True"></Setter>
                </Style>
            </TreeView.ItemContainerStyle>
private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            var dic = new Dictionary<string, Dictionary<string, string>>();
            var item1 = new Dictionary<string, string>();
            item1.Add("key1", "value");
            item1.Add("key", "value");
            dic.Add("1", item1);

            var item2 = new Dictionary<string, string>();
            item2.Add("Name:", "zhangsan");
            item2.Add("Age:", "12");
            dic.Add("2", item2);
            treeView.ItemsSource = dic;
        }

 

对两处Binding 的Value进行说明:

WPF TreeView控件中绑定嵌套的Dictionary<string, Dictionary<string, string>>集合

 

 

 效果如下图

WPF TreeView控件中绑定嵌套的Dictionary<string, Dictionary<string, string>>集合

 

WPF TreeView控件中绑定嵌套的Dictionary<string, Dictionary<string, string>>集合

上一篇:C#日期与时间


下一篇:TcMalloc的介绍以及Windows下安装使用