MVVM / ObservableCollection Question

后端 未结 6 940
陌清茗
陌清茗 2021-01-19 15:32

I have the following XAML:

   
        

        
相关标签:
6条回答
  • 2021-01-19 15:47

    You are changing the instance of observable collection, not the contents of the observable collection. So the collection has nothing to notify about.

    0 讨论(0)
  • 2021-01-19 15:49

    ObservableCollection knows how to notify if the collection changes i.e. an item is added or removed.

    however, if you do the following:

    FamilyList = new ObservableCollection<FamilyList>(); 
    // or
    FamilyList = GetFamilyList();
    

    then you are actually changing the property that holds your collection, which is different. I'm guessing this is the issue here.

    0 讨论(0)
  • 2021-01-19 15:58

    As long as the property holding the collection has been created before the list is bound/DataContext set, you should be ok. If the collection is replaced, as @Phil Sandler says, you need to notify. If you create you only perform new when declaring the variable, or inside of the constructor of the class, you should not need notify property changed for that property. If you need to clear the list, I would recommend using the Clear method of the collection, and not replace it.

    0 讨论(0)
  • 2021-01-19 16:03

    The ObservableCollection's implementation of INotifyPropertyChanged is basically used to react to adding to or removing from that collection.

    You need to call Notify...() in the setter, because the collection is a property of your ViewModel and the DataGrid will not react to any changes of your ViewModel's properties, unless you call Notify...() when changed.

    Edit: I'm too slow.

    0 讨论(0)
  • 2021-01-19 16:08

    ObservableCollection<T> implements INotifyCollectionChanged which informs a registered event handler about changes in the collection (add,remove,sort of items). However the DataGrid must know if a property of one of your business-objects has changed to update the value in the grid. For this, INotifyPropertyChanged is needed.
    ObservableCollection<T> implements also INotifyCollectionChanged. However this can only be used to be informed if a property of the collection has been changed. There is no mechanism that let the collection detect if your business object has been changed (and if it would have, it would register to INotifyCollectionChanged of your business object :).

    0 讨论(0)
  • 2021-01-19 16:09

    You should not need to notify if the collection itself adds or removes items. However, if you swap the whole collection out with a new/different instance (i.e. familyList = new ObservableCollection<Services.Family>()) you need to notify. If you are indeed changing the instance, consider clearing/repopulating the collection instead.

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