WPF TreeView控件绑定到的ObservableCollection没有更新根节点 [英] WPF TreeView bound to ObservableCollection not updating root nodes

查看:1161
本文介绍了WPF TreeView控件绑定到的ObservableCollection没有更新根节点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对不起 - 我的问题是几乎相同的这一个但因为它没有得到一个可行的答案,我希望其他人有一些新的想法。

Sorry - my question is almost identical to this one but since it didn't receive a viable answer, I am hoping that someone else has some fresh ideas.

我有一个绑定到一个单一类型的层次结构中的WPF的TreeView:

I have a WPF TreeView that is bound to a hierarchy of a single type:

public class Entity
{
    public string Title { get; set; }
    public ObservableCollection<Entity> Children { get; set; }
}

实体类实现INotifyPropertyChanged,但我已经省略此code为清晰。

The Entity class implements INotifyPropertyChanged, but I have omitted this code for clarity.

该TreeView控件绑定到一个ObservableCollection&LT;实体>每个实体实例,通过它的儿童财产公开了一组包含的实体实例:

The TreeView is bound to an ObservableCollection<Entity> and each Entity instance exposes a set of contained Entity instances via its Children property:

<TreeView ItemsSource="{Binding Path=Entities}">
    <TreeView.Resources>
        <HierarchicalDataTemplate DataType="{x:Type local:Entity}" ItemsSource="{Binding Path=Children}">
           <TextBlock Text="{Binding Path=Title}" />
        </HierarchicalDataTemplate>
   </TreeView.Resources>
</TreeView>

最初的TreeView结合预期和正确显示的多层次结构。此外,当孩子们的收藏品之一的成员以编程方式修改,更改正确反映在TreeView。

Initially the TreeView binds as expected and correctly displays a multi-level hierarchy. Also, when the membership of one of the Children collections is programmatically modified, the changes are correctly reflected in the TreeView.

但是,更改到根成员级别的ObservableCollection&LT的成员;实体>不会反映在TreeView

However, changes to the membership of the root member level ObservableCollection<Entity> are not reflected in the TreeView.

任何建议将是AP preciated。

Any suggestions would be appreciated.

谢谢,
蒂姆·

Thanks, Tim

推荐答案

我最初的猜测是,你有类似的根节点以下内容:

My initial guess is that you have something like the following for the root node:

public ObservableCollection<Entity> Entities
{
    get;
    set;
}

然后,而不是做一些[好]这样的:

Then, instead of doing something [good] like the following:

Entities.Clear();
foreach (var item in someSetOfItems)
    Entities.Add(item);

您正在做的事情[衰]是这样的:

You are doing something [bad] like this:

Entities = new ObservableCollection<Entity>(someSetOfItems);

您应该能够通过使实体属性的支持字段追查问题只读

You should be able to track down the issue by making the backing field of the Entities property readonly:

private readonly ObservableCollection<Entity> _entities
    = new ObservableCollection<Entity>();

public ObservableCollection<Entity> Entities
{
    get
    {
        return _entities;
    }
}

这篇关于WPF TreeView控件绑定到的ObservableCollection没有更新根节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆