Geeks With Blogs
David Vallens

The ObservableCollection implements the INotifyCollectionChanged interface, which fires the CollectionChanged event when the collection is changed. One of the great things about this event is its argument NotifyCollectionChangedEventArgs provides 2 lists (which can be null) NewItems OldItems, which make it easy to seem whats been added/deleted from the collection.

The INotifyCollectionChanged interface make it easy to manage tasks relating to the contents of the collection, ie setting the parent etc. It also makes it possible to construct facade's (ViewModel) objects that pass through events as well as property values (See Constructing View Model Facade classes).

 But be warned!

When you call clear on the list the CollectionChanged event is fired with the action set to Reset, BUT the OldItems list is empty. Whats worse is at the point when this event reaches your code the items have already been removed from the collection, leaving you unable to perform the processing on them.

My Solution to this is to create my own collection class which derives from ObservableCollection, and fires the events that shows all the items being removed.



    public class ObservableCollectionEx : ObservableCollection
        public ObservableCollectionEx() : base() { }
        public ObservableCollectionEx(IEnumerable collection) : base(collection) { }
        public ObservableCollectionEx(List list) : base(list) { }

        protected override void ClearItems()
            List oldItems = new List(this);

            this.OnPropertyChanged(new System.ComponentModel.PropertyChangedEventArgs("Count"));
            this.OnPropertyChanged(new System.ComponentModel.PropertyChangedEventArgs("Item[]"));
            this.OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove, oldItems, 0));


I'm not holding this up as the best solution, but it works for me, for a full discussion see this StackOverflow thread.

Posted on Friday, April 1, 2011 5:08 AM WPF , MVVM | Back to top

Comments on this post: When calling ObservableCollection.Clear OldItems is empty

No comments posted yet.
Your comment:
 (will show your gravatar)

Copyright © David Vallens | Powered by: