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

前端 未结 20 1808
不知归路
不知归路 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:54

    Well, I decided to get dirty with it myself.

    Microsoft put a LOT of work into always making sure the NotifyCollectionChangedEventArgs doesn't have any data when calling a reset. I'm assuming this was a performance/memory decision. If you are resetting a collection with 100,000 elements, I'm assuming they didn't want to duplicate all those elements.

    But seeing as my collections never have more then 100 elements, I don't see a problem with it.

    Anyway I created an inherited class with the following method:

    protected override void ClearItems()
    {
        CheckReentrancy();
        List oldItems = new List(Items);
    
        Items.Clear();
    
        OnPropertyChanged(new PropertyChangedEventArgs("Count"));
        OnPropertyChanged(new PropertyChangedEventArgs("Item[]"));
    
        NotifyCollectionChangedEventArgs e =
            new NotifyCollectionChangedEventArgs
            (
                NotifyCollectionChangedAction.Reset
            );
    
            FieldInfo field =
                e.GetType().GetField
                (
                    "_oldItems",
                    BindingFlags.Instance | BindingFlags.NonPublic
                );
            field.SetValue(e, oldItems);
    
            OnCollectionChanged(e);
        }
    

提交回复
热议问题