what is notifycollectionchangedaction reset value

后端 未结 3 996
一整个雨季
一整个雨季 2020-12-06 16:22

I have an observable collection...SelectableDataContext..And in the generic class SelectableDataContext is...having two private m

3条回答
  •  暖寄归人
    2020-12-06 17:21

    This is an old question but for the benefit of anyone who may come across this through a search as I did:

    NotifyCollectionChangedAction.Reset means "The content of the collection changed dramatically". One case where the Reset event is raised is when you call Clear() on the underlying observable collection.

    With the Reset event, you don't get the NewItems and OldItems collections in the NotifyCollectionChangedEventArgs parameter.

    This means you're better off using the "sender" of the event to get a reference to the modified collection and use that directly, i.e. assume it's a new list.

    An example of this might be something like:

    ((INotifyCollectionChanged)stringCollection).CollectionChanged += new NotifyCollectionChangedEventHandler(StringCollection_CollectionChanged);
      ...
    
    void StringCollection_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
    {
        switch (e.Action)
        {
            case NotifyCollectionChangedAction.Add:
                foreach (string s in e.NewItems)
                {
                    InternalAdd(s);
                }
                break;
    
            case NotifyCollectionChangedAction.Remove:
                foreach (string s in e.OldItems)
                {
                    InternalRemove(s);
                }
                break;
    
            case NotifyCollectionChangedAction.Reset:
                ReadOnlyObservableCollection col = sender as ReadOnlyObservableCollection;
                InternalClearAll();
                if (col != null)
                {
                    foreach (string s in col)
                    {
                        InternalAdd(s);
                    }
                }
                break;
        }
    }
    

    Lots of discussions on this Reset event here: When Clearing an ObservableCollection, There are No Items in e.OldItems.

提交回复
热议问题