Tim*_*ter 9 wpf treeview binding observablecollection root-node
对不起 - 我的问题与此问题几乎相同,但由于没有得到可行的答案,我希望其他人有一些新的想法.
我有一个绑定到单一类型的层次结构的WPF TreeView:
public class Entity
{
    public string Title { get; set; }
    public ObservableCollection<Entity> Children { get; set; }
}
Entity类实现了INotifyPropertyChanged,但为了清楚起见,我省略了这段代码.
TreeView绑定到ObservableCollection <Entity>,每个Entity实例通过其Children属性公开一组包含的Entity实例:
<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中.
但是,对根成员级别ObservableCollection <Entity>的成员身份的更改不会反映在TreeView中.
任何建议,将不胜感激.
蒂姆,谢谢
Sam*_*ell 21
我最初的猜测是你对根节点有如下内容:
public ObservableCollection<Entity> Entities
{
    get;
    set;
}
然后,而不是像以下那样做[好]的事情:
Entities.Clear();
foreach (var item in someSetOfItems)
    Entities.Add(item);
你正在做这样的事情[糟糕]:
Entities = new ObservableCollection<Entity>(someSetOfItems);
您应该能够通过创建实体属性的支持字段来追踪问题readonly:
private readonly ObservableCollection<Entity> _entities
    = new ObservableCollection<Entity>();
public ObservableCollection<Entity> Entities
{
    get
    {
        return _entities;
    }
}