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);
}
}