我正在使用 WPF TreeView 控件,我已将其绑定到基于 ObservableCollections 的简单树结构。这是 XAML:
<TreeView Name="tree" Grid.Row="0">
<TreeView.ItemTemplate>
<HierarchicalDataTemplate ItemsSource="{Binding Path=Children}">
<TextBlock Text="{Binding Path=Text}"/>
</HierarchicalDataTemplate>
</TreeView.ItemTemplate>
</TreeView>
和树结构:
public class Node : IEnumerable {
private string text;
private ObservableCollection<Node> children;
public string Text { get { return text; } }
public ObservableCollection<Node> Children { get { return children; } }
public Node(string text, params string[] items){
this.text = text;
children = new ObservableCollection<Node>();
foreach (string item in items)
children.Add(new Node(item));
}
public IEnumerator GetEnumerator() {
for (int i = 0; i < children.Count; i++)
yield return children[i];
}
}
我将这棵树的 ItemsSource 设置为我的树结构的根,并且它的子节点成为树中的根级项(正如我想要的那样):
private Node root;
root = new Node("Animals");
for(int i=0;i<3;i++)
root.Children.Add(new Node("Mammals", "Dogs", "Bears"));
tree.ItemsSource = root;
我可以将新的子节点添加到树结构的各种非根节点中,它们会出现在 TreeView 中它们应该出现的位置。
root.Children[0].Children.Add(new Node("Cats", "Lions", "Tigers"));
但是,如果我将一个子节点添加到根节点:
root.Children.Add(new Node("Lizards", "Skinks", "Geckos"));
该项目没有出现,并且我没有尝试过(例如将 ItemsSource 设置为 null 然后再返回)导致它出现。
如果我在设置 ItemsSource 之前添加蜥蜴,它们会显示出来,但如果我之后添加它们则不会。
有任何想法吗?