首页 文章

WPF - 绑定树视图不更新根项

提问于
浏览
1

我正在使用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之前添加蜥蜴,它们会显示,但是如果我之后添加它们则不会显示 .

The cats appear, but not the lizards

有任何想法吗?

2 回答

  • 2

    您正在设置ItemsSource = root,它恰好实现了IEnumerable,但它本身并不可观察 . 即使你有一个可观察的Children属性,也不是你绑定TreeView的东西,所以TreeView没有任何方法可以监听通过Children属性发生的变化 .

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

  • 3

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

相关问题