如何避免射击ObservableCollection.CollectionChanged多次更换所有元素或添加元素的集合 [英] How to Avoid Firing ObservableCollection.CollectionChanged Multiple Times When Replacing All Elements Or Adding a Collection of Elements

查看:299
本文介绍了如何避免射击ObservableCollection.CollectionChanged多次更换所有元素或添加元素的集合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

的ObservableCollection< T> 集合,我想与元素的一个新的集合,以取代所有元素,我可以这样做:

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

collection.Clear(); 

collection.ClearItems();

(顺便说一句,什么是这两种方法之间的区别?)

(BTW, what's the difference between these two methods?)

我也可以使用的foreach collection.Add 一个接一个,但是这将触发多次

I could also use foreach to collection.Add one by one, but this will fire multiple times

添加元素的集合时一样。

Same when adding a collection of elements.

编辑:

我找到了一个好的图书馆在这里:增强的ObservableCollection与延迟的能力或禁用通知的,但它似乎不支持Silverlight的。

I found a good library here: Enhanced ObservableCollection with ability to delay or disable notifications but it seems that it does NOT support silverlight.

推荐答案

啉是对他的所有信息。我只想补充我的的ObservableCollection 的子类,我用这种特殊情况下。

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

这篇关于如何避免射击ObservableCollection.CollectionChanged多次更换所有元素或添加元素的集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆