WPF TreeView bound to ObservableCollection not updating root nodes

后端 未结 2 845
天涯浪人
天涯浪人 2020-12-31 15:18

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.

I have a WPF Tr

相关标签:
2条回答
  • 2020-12-31 15:46

    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;
        }
    }
    
    0 讨论(0)
  • 2020-12-31 16:04

    Further explanation, long time for answer to come, but I believe that if you do the binding in XAML, and then in code assign a new object to the property you break the binding, so you would have to redo the binding in code for it to work. Hence the solution with the readonly backing field. If doing like that you will not be able to assign a new ObservableCollection and you won't break the binding by assigning a new object to the backing field.

    0 讨论(0)
提交回复
热议问题