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

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

    I found another "simple" solution deriving from ObservableCollection, but it is not very elegant because it uses Reflection... If you like it here is my solution:

    public class ObservableCollectionClearable : ObservableCollection
    {
        private T[] ClearingItems = null;
    
        protected override void OnCollectionChanged(System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
        {
            switch (e.Action)
            {
                case System.Collections.Specialized.NotifyCollectionChangedAction.Reset:
                    if (this.ClearingItems != null)
                    {
                        ReplaceOldItems(e, this.ClearingItems);
                        this.ClearingItems = null;
                    }
                    break;
            }
            base.OnCollectionChanged(e);
        }
    
        protected override void ClearItems()
        {
            this.ClearingItems = this.ToArray();
            base.ClearItems();
        }
    
        private static void ReplaceOldItems(System.Collections.Specialized.NotifyCollectionChangedEventArgs e, T[] olditems)
        {
            Type t = e.GetType();
            System.Reflection.FieldInfo foldItems = t.GetField("_oldItems", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
            if (foldItems != null)
            {
                foldItems.SetValue(e, olditems);
            }
        }
    }
    

    Here I save the current elements in an array field in the ClearItems method, then I intercept the call of OnCollectionChanged and overwrite the e._oldItems private field (through Reflections) before launching base.OnCollectionChanged

提交回复
热议问题