When Clearing an ObservableCollection, There are No Items in e.OldItems

前端 未结 20 1828
不知归路
不知归路 2020-11-30 00:27

I have something here that is really catching me off guard.

I have an ObservableCollection of T that is filled with items. I also have an event handler attached to t

20条回答
  •  广开言路
    2020-11-30 00:52

    Okay, I know this is a very old question but I have come up with a good solution to the issue and thought I would share. This solution takes inspiration from a lot of the great answers here but has the following advantages:

    • No need to create a new class and override methods from ObservableCollection
    • Does not tamper with the workings of NotifyCollectionChanged (so no messing with Reset)
    • Does not make use of reflection

    Here is the code:

     public static void Clear(this ObservableCollection collection, Action> unhookAction)
     {
         unhookAction.Invoke(collection);
         collection.Clear();
     }
    

    This extension method simply takes an Action which will be invoked before the collection is cleared.

提交回复
热议问题