Geeks With Blogs
New Things I Learned

While trying to sort out a different problem, I ended up looking at the NotifyCollectionChangedEventArgs constructor where the first overload only needs a NotifyCollectionChangedAction enumeration with no items needed.  It must've escaped my mind since most of the implementation I had so far will actually raise the CollectionChanged event when adding or removing an item, and most of those implementation will just specify the item being added/removed.

This single parameter constructor documentation specifies the action has to be NotifyCollectionChangedAction.Reset.  It piques my interest to learn more as to what Reset does.  The documentation states that Reset means 'The content of the collection changed dramatically'.  I remembered one of my post where I complained that CollectionView does not support multiple items being added/removed, and my solution then was to call the Refresh method of the CollectionView, which even though it's fine, it's very CollectionView specific.

So I went through my test projects, and voila, CollectionView accepts (and behave appropriately) the Reset action.  As such, the code to handle CollectionView becomes much simpler:

public class MyObservableCollection<T> : ObservableCollection<T>

{

   private bool _delayCollectionChangeNotification = false;

   // Want to delay change notification when inserting multiple items

   public bool DelayCollectionChangeNotification

   {

      get { return _delayCollectionChangeNotification; }

      set

      {

         if (_delayCollectionChangeNotification != value)

         {

            _delayCollectionChangeNotification = value;

            if (value == false)

               OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));

         }

      }

   }

 

   public void AddRange(IEnumerable<T> items)

   {

      DelayCollectionChangeNotification = true;

      foreach (T item in items)

      {

         Add(item);

      }

      DelayCollectionChangeNotification = false;

   }

 

   protected override void OnCollectionChanged(System.Collections.Specialized.NotifyCollectionChangedEventArgs e)

   {

      if (_delayCollectionChangeNotification == false)

         base.OnCollectionChanged(e);

   }

}

No more need to walk thru the event subscriber, and you can somewhat control it from the outside thru the DelayCollectionChangeNotification property.  I learned something new today...

Posted on Friday, January 25, 2008 12:10 PM WPF , .NET | Back to top


Comments on this post: An alternative to notifying CollectionView of multiple items changed

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


Copyright © Muljadi Budiman | Powered by: GeeksWithBlogs.net | Join free