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

前端 未结 5 2061

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

collection.Cl         


        
5条回答
  •  难免孤独
    2020-11-27 05:59

    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).

提交回复
热议问题