gpt4 book ai didi

c# - 如何避免在替换所有元素或添加元素集合时多次触发 ObservableCollection.CollectionChanged

转载 作者:IT王子 更新时间:2023-10-29 03:55:29 26 4
gpt4 key购买 nike

我有ObservableCollection<T>集合,我想用新的元素集合替换所有元素,我可以这样做:

collection.Clear(); 

或:

collection.ClearItems();

(顺便说一句,这两种方法有什么区别?)

我也可以使用 foreachcollection.Add一个接一个,但这会触发多次

添加元素集合时相同。

编辑:

我在这里找到了一个很好的图书馆:Enhanced ObservableCollection with ability to delay or disable notifications但它似乎不支持 silverlight。

最佳答案

ColinE 的所有信息都是正确的。我只想添加我用于此特定情况的 ObservableCollection 的子类。

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

关于c# - 如何避免在替换所有元素或添加元素集合时多次触发 ObservableCollection.CollectionChanged,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13302933/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com