WPF TreeView 绑定到 ObservableCollection 不更新根节点 [英] WPF TreeView bound to ObservableCollection not updating root nodes

查看:39
本文介绍了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; }
}

Entity 类实现了 INotifyPropertyChanged,但为了清楚起见,我省略了这段代码.

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

TreeView 绑定到一个 ObservableCollection 并且每个 Entity 实例通过其 Children 属性公开一组包含的 Entity 实例:

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 按预期绑定并正确显示多级层次结构.此外,当以编程方式修改 Children 集合之一的成员资格时,更改会正确反映在 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 的成员资格的更改不会反映在 TreeView 中.

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

如有任何建议,我们将不胜感激.

Any suggestions would be appreciated.

谢谢,提姆

推荐答案

我最初的猜测是您的根节点有如下类似内容:

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);

您应该能够通过将 Entities 属性的支持字段设为 readonly 来追踪问题:

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天全站免登陆