【问题标题】:WPF - Bound treeview not updating root itemsWPF - 绑定树视图不更新根项目
【发布时间】: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


【解决方案1】:

如果 'root' 是 ObservableCollection,您的树视图将更新。 'root' 是可观察集合,还是 root 是可观察集合中的节点?查看您对项目源的绑定将有助于回答这个问题。当您在代码中分配它时,您可能只是将其设置为单个元素,而不是集合

【讨论】:

  • 我已经用相关的细节更新了这个问题——“root”和其他所有节点一样只是一个节点。它不会出现在 TreeView 本身中,但这很好。如果我创建一个可观察的 NodeCollection 并将其用作根,它没有任何区别。
【解决方案2】:

您正在设置 ItemsSource = root,它恰好实现了 IEnumerable,但它本身不是可观察的。即使您有一个可观察的 Children 属性,但这并不是您将 TreeView 绑定到的内容,因此 TreeView 没有任何方式监听通过 Children 属性发生的更改。

我会完全从 Node 类中删除 IEnumerable。然后设置 treeView.ItemsSource = root.Children;

【讨论】:

    猜你喜欢
    • 2014-10-20
    • 2012-02-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-07
    相关资源
    最近更新 更多