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

前端 未结 12 1453
走了就别回头了
走了就别回头了 2020-11-22 16:19

I want to be able to add a range and get updated for the entire bulk.

I also want to be able to cancel the action before it\'s done (i.e. collection changing besides

12条回答
  •  北恋
    北恋 (楼主)
    2020-11-22 16:40

    As there might be a number of operations to do on an ObservableCollection for example Clear first then AddRange and then insert "All" item for a ComboBox I ended up with folowing solution:

    public static class LinqExtensions
    {
        public static ICollection AddRange(this ICollection source, IEnumerable addSource)
        {
            foreach(T item in addSource)
            {
                source.Add(item);
            }
    
            return source;
        }
    }
    
    public class ExtendedObservableCollection: ObservableCollection
    {
        public void Execute(Action> itemsAction)
        {
            itemsAction(Items);
            OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
        }
    }
    

    And example how to use it:

    MyDogs.Execute(items =>
    {
        items.Clear();
        items.AddRange(Context.Dogs);
        items.Insert(0, new Dog { Id = 0, Name = "All Dogs" });
    });
    

    The Reset notification will be called only once after Execute is finished processing the underlying list.

提交回复
热议问题