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.
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); } }
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With