【发布时间】:2019-06-07 14:01:21
【问题描述】:
我将树状数据存储在 Dictionary 中,声明如下:
Dictionary<string, object>
string 是一个标签,object 可以是以下之一:
- 一个
string -
int - 嵌套的
Dictionary<string, object>
我正在尝试使用此 XAML 将其显示在 TreeView 中:
<TreeView Background="Black" Foreground="Yellow" ItemsSource="{Binding}">
<TreeView.ItemTemplate>
<HierarchicalDataTemplate ItemsSource="{Binding Path=Value}">
<TextBlock Foreground="Red" Text="{Binding Path=Key}" />
<HierarchicalDataTemplate.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock Foreground="LightGreen" Text="{Binding Path=Key}"/>
<TextBlock Foreground="White" Text="="/>
<TextBlock Foreground="Yellow" Text="{Binding Path=Value}"/>
</StackPanel>
</DataTemplate>
</HierarchicalDataTemplate.ItemTemplate>
</HierarchicalDataTemplate>
</TreeView.ItemTemplate>
</TreeView>
这适用于顶级,但添加另一个级别如下所示:
有了这些数据:
变量 1... child1 =“你好” child2 =“那里” 孩子3... sub1 =“如何” sub2 = “是” sub3 =“你” 变量2... child1 = "lorem" child2 = "ipsum"因此,当子对象为string 或int 时,它可以工作,但当它是Dictionary 时,它只是将其转换为字符串,而不是递归处理它。
我怎样才能让这些数据显示出来?
编辑: 构建树的代码:
Dictionary<string, object> data = new Dictionary<string, object>();
Dictionary<string, object> child = new Dictionary<string, object>();
child["child1"] = "hello";
child["child2"] = "there";
Dictionary<string, object> child2 = new Dictionary<string, object>();
child2["sub1"] = "how";
child2["sub2"] = "are";
child2["sub3"] = "you";
child["child3"] = child2;
data["Variable1"] = child;
child = new Dictionary<string, object>();
child["child1"] = "lorem";
child["child2"] = "ipsum";
data["Variable2"] = child;
variablesWindow.DataContext = data;
【问题讨论】: