ObservableCollection and batch modification
In C#, the ObservableCollection<T>
class provides a way to track changes to collection items and notify observers that changes occur. However, this class does not support the AddRange
method.
To solve this problem, you can implement your own ObservableRangeCollection
class, which supports adding multiple items at once. Here is the updated and optimized version in C# 7:
<code class="language-csharp">using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Collections.Specialized; public class ObservableRangeCollection<T> : ObservableCollection<T> { public void AddRange(IEnumerable<T> collection) { if (collection == null) throw new ArgumentNullException(nameof(collection)); foreach (var item in collection) Items.Add(item); OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset)); } public void RemoveRange(IEnumerable<T> collection) { if (collection == null) throw new ArgumentNullException(nameof(collection)); foreach (var item in collection) Items.Remove(item); OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset)); } public void Replace(T item) { ReplaceRange(new[] { item }); } public void ReplaceRange(IEnumerable<T> collection) { if (collection == null) throw new ArgumentNullException(nameof(collection)); Items.Clear(); foreach (var item in collection) Items.Add(item); OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset)); } }</code>
This implementation allows you to add or remove multiple items to a collection in one operation, and it will notify observers of the changes via OnCollectionChanged
events.
Handling collection modifications
If you want to handle collection modifications before they occur (for example, show a confirmation dialog), you can implement the INotifyCollectionChanging
interface:
<code class="language-csharp">public interface INotifyCollectionChanging<T> { event NotifyCollectionChangingEventHandler<T> CollectionChanging; }</code>
<code class="language-csharp">public class ObservableRangeCollection<T> : ObservableCollection<T>, INotifyCollectionChanging<T> { // ... protected override void ClearItems() { var e = new NotifyCollectionChangingEventArgs<T>(NotifyCollectionChangedAction.Reset, Items); OnCollectionChanging(e); if (e.Cancel) return; base.ClearItems(); } // ... public event NotifyCollectionChangingEventHandler<T> CollectionChanging; protected virtual void OnCollectionChanging(NotifyCollectionChangingEventArgs<T> e) { CollectionChanging?.Invoke(this, e); } }</code>
This way you can handle the CollectionChanging
event to cancel or modify the collection modification operation.
The above is the detailed content of How Can I Efficiently Add and Remove Ranges of Items from an ObservableCollection in C#?. For more information, please follow other related articles on the PHP Chinese website!