I have ObservableCollection
collection, and I want to replace all elements with a new collection of elements, I could do:
collection.Cl
For the past few years I am using a more generic solution to eliminate too many ObservableCollection notifications by creating a batch change operation and notifying observers with a Reset action:
public class ExtendedObservableCollection: ObservableCollection
{
public ExtendedObservableCollection()
{
}
public ExtendedObservableCollection(IEnumerable items)
: base(items)
{
}
public void Execute(Action> itemsAction)
{
itemsAction(Items);
OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
}
}
Using it is straightforward:
var collection = new ExtendedObservableCollection(new[]
{
"Test",
"Items",
"Here"
});
collection.Execute(items => {
items.RemoveAt(1);
items.Insert(1, "Elements");
items.Add("and there");
});
Calling Execute will generate a single notification but with a drawback - list will be updated in UI as a whole, not only modified elements. This makes it perfect for items.Clear() followed by items.AddRange(newItems).