ObservableCollection<...>
添加项目,而且确实有很多项目。现在我想知道,每次我向集合中添加一个项目时,它是否会立即触发事件并导致不必要的开销?如果是这样,我是否可以暂时禁用事件通知,并在我的代码结尾手动触发它,以便如果我添加了10k个项目,它只会被触发一次,而不是10k次?
更新:我尝试使用以下类:
using System;
using System.Linq;
using System.Collections.Specialized;
using System.Collections.Generic;
namespace MyProject
{
/// <summary>
/// Represents a dynamic data collection that provides notifications when items get added, removed, or when the whole list is refreshed.
/// </summary>
/// <typeparam name="T"></typeparam>
public class ObservableCollection<T> : System.Collections.ObjectModel.ObservableCollection<T>
{
/// <summary>
/// Adds the elements of the specified collection to the end of the ObservableCollection(Of T).
/// </summary>
public void AddRange(IEnumerable<T> collection)
{
foreach (var i in collection) Items.Add(i);
OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, collection.ToList()));
}
/// <summary>
/// Removes the first occurence of each item in the specified collection from ObservableCollection(Of T).
/// </summary>
public void RemoveRange(IEnumerable<T> collection)
{
foreach (var i in collection) Items.Remove(i);
OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove, collection.ToList()));
}
/// <summary>
/// Clears the current collection and replaces it with the specified item.
/// </summary>
public void Replace(T item)
{
ReplaceRange(new T[] { item });
}
/// <summary>
/// Clears the current collection and replaces it with the specified collection.
/// </summary>
public void ReplaceRange(IEnumerable<T> collection)
{
List<T> old = new List<T>(Items);
Items.Clear();
foreach (var i in collection) Items.Add(i);
OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Replace, collection.ToList()));
}
/// <summary>
/// Initializes a new instance of the System.Collections.ObjectModel.ObservableCollection(Of T) class.
/// </summary>
public ObservableCollection() : base() { }
/// <summary>
/// Initializes a new instance of the System.Collections.ObjectModel.ObservableCollection(Of T) class that contains elements copied from the specified collection.
/// </summary>
/// <param name="collection">collection: The collection from which the elements are copied.</param>
/// <exception cref="System.ArgumentNullException">The collection parameter cannot be null.</exception>
public ObservableCollection(IEnumerable<T> collection) : base(collection) { }
}
}
我现在遇到这个错误:
附加信息:不支持范围操作。
错误出现在这里:
OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, collection.ToList()));
NotifyCollectionChangedAction.Reset
值的作用是什么,并提供了处理它的方法。https://dev59.com/hG855IYBdhLWcg3wKxDc - Tim RutterObservableCollection<T>
对象。原始的ObservableCollection
每行更新 UI 需要约 90 微秒。而这里的可抑制版本每行只需要约 15 微秒。 - AlainD