代码之家  ›  专栏  ›  技术社区  ›  Joel Rein

WPF绑定的树视图不更新根项目

  •  1
  • Joel Rein  · 技术社区  · 16 年前

    我使用的是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; 
    

    root.Children[0].Children.Add(new Node("Cats", "Lions", "Tigers"));  

    但是,如果向根节点添加子节点:

    root.Children.Add(new Node("Lizards", "Skinks", "Geckos")); 

    The cats appear, but not the lizards

    有什么想法吗?

    2 回复  |  直到 16 年前
        1
  •  3
  •   Josh    16 年前

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

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

        2
  •  2
  •   Aran Mulholland JohnnyAce    16 年前

    如果“root”是可观察的集合,则您的treeview将更新。“根”是可观察的集合,还是根是可观察集合中的节点?查看条目源的绑定将有助于回答这个问题。在代码中分配它时,可能只是将其设置为单个元素,而不是集合