【发布时间】:2010-12-26 06:56:09
【问题描述】:
我正在使用 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 之前添加蜥蜴,它们会显示出来,但如果我之后添加它们则不会。
有什么想法吗?
【问题讨论】:
-
你在使用什么 observableCollection,这个msdn.microsoft.com/en-us/library/ms668604.aspx ?因为在你上面的代码中看起来像一个非通用版本,你自己推出了吗?
-
那是我的错 - 由于尖括号,没有显示类型参数。是的,我使用的是标准的通用 ObservableCollection。
-
你找到解决这个问题的方法了吗?我有完全相同的问题,并希望您能提供任何指导。谢谢。
-
乔什爱因斯坦的回答解决了我的问题 - 将 ItemsSource 设置为 root.Children。不知道这是否能解决您的问题。
标签: c# wpf binding treeview itemssource