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

前端 未结 5 2068

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 06:11

    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 : ObservableCollection {
        public SmartCollection()
            : base() {
        }
    
        public SmartCollection(IEnumerable collection)
            : base(collection) {
        }
    
        public SmartCollection(List list)
            : base(list) {
        }
    
        public void AddRange(IEnumerable 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 range) {
            this.Items.Clear();
    
            AddRange(range);
        }
    }
    

提交回复
热议问题