Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Avoid Firing ObservableCollection.CollectionChanged Multiple Times When Replacing All Elements Or Adding a Collection of Elements

I have ObservableCollection<T> collection, and I want to replace all elements with a new collection of elements, I could do:

collection.Clear();  

OR:

collection.ClearItems(); 

(BTW, what's the difference between these two methods?)

I could also use foreach to collection.Add one by one, but this will fire multiple times

Same when adding a collection of elements.

EDIT:

I found a good library here: Enhanced ObservableCollection with ability to delay or disable notifications but it seems that it does NOT support silverlight.

like image 555
Peter Lee Avatar asked Nov 09 '12 06:11

Peter Lee


2 Answers

ColinE is right with all his informations. I only want to add my subclass of ObservableCollection that I use for this specific case.

public class SmartCollection<T> : ObservableCollection<T> {     public SmartCollection()         : base() {     }      public SmartCollection(IEnumerable<T> collection)         : base(collection) {     }      public SmartCollection(List<T> list)         : base(list) {     }      public void AddRange(IEnumerable<T> range) {         foreach (var item in range) {             Items.Add(item);         }          this.OnPropertyChanged(new PropertyChangedEventArgs("Count"));         this.OnPropertyChanged(new PropertyChangedEventArgs("Item[]"));         this.OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));     }      public void Reset(IEnumerable<T> range) {         this.Items.Clear();          AddRange(range);     } } 
like image 177
Jehof Avatar answered Sep 19 '22 14:09

Jehof


You can achieve this by subclassing ObservableCollection and implementing your own ReplaceAll method. The implementation of this methods would replace all the items within the internal Items property, then fire a CollectionChanged event. Likewise, you can add an AddRange method. For an implementation of this, see the answer to this question:

ObservableCollection Doesn't support AddRange method, so I get notified for each item added, besides what about INotifyCollectionChanging?

The difference between Collection.Clear and Collection.ClearItems is that Clear is a public API method, whereas ClearItems is protected, it is an extension point that allows your to extend / modify the behaviour of Clear.

like image 45
ColinE Avatar answered Sep 20 '22 14:09

ColinE