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

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

    I was just going through some of the charting code in the Silverlight and WPF toolkits and noticed that they also solved this problem (in a kind of similar way) ... and I thought I would go ahead and post their solution.

    Basically, they also created a derived ObservableCollection and overrode ClearItems, calling Remove on each item being cleared.

    Here is the code:

    /// 
    /// An observable collection that cannot be reset.  When clear is called
    /// items are removed individually, giving listeners the chance to detect
    /// each remove event and perform operations such as unhooking event 
    /// handlers.
    /// 
    /// The type of item in the collection.
    public class NoResetObservableCollection : ObservableCollection
    {
        public NoResetObservableCollection()
        {
        }
    
        /// 
        /// Clears all items in the collection by removing them individually.
        /// 
        protected override void ClearItems()
        {
            IList items = new List(this);
            foreach (T item in items)
            {
                Remove(item);
            }
        }
    }
    

提交回复
热议问题