using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Collections.Specialized; using System.ComponentModel; namespace FruitBank.Common { public interface IFastObservableCollection { public void AddRange(IEnumerable other); public void Replace(IEnumerable other); public void RemoveRange(IEnumerable other); public void Synchronize(NotifyCollectionChangedEventArgs args); } public interface IFastObservableCollection: IFastObservableCollection { public void Replace(IEnumerable other); public void Sort(IComparer comparer); public void SortAndReplace(IEnumerable other, IComparer comparer); } public class FastObservableCollection : ObservableCollection, IFastObservableCollection { private bool suppressChangedEvent = false; public void Replace(IEnumerable other) { suppressChangedEvent = true; Clear(); AddRange(other); } public void Replace(IEnumerable other) { suppressChangedEvent = true; Clear(); foreach (T item in other) Add(item); suppressChangedEvent = false; OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset)); OnPropertyChanged(new(nameof(Count))); } public void AddRange(IEnumerable other) { suppressChangedEvent = true; foreach (object item in other) { if (item is T tItem) Add(tItem); } suppressChangedEvent = false; OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset)); OnPropertyChanged(new(nameof(Count))); } public void RemoveRange(IEnumerable other) { suppressChangedEvent = true; foreach (object item in other) { if (item is T tItem) Remove(tItem); } suppressChangedEvent = false; OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset)); OnPropertyChanged(new(nameof(Count))); } public void SortAndReplace(IEnumerable other, IComparer comparer) { List values = new(other); values.Sort(comparer); Replace(values); } public void Sort(IComparer comparer) { List values = new(this); values.Sort(comparer); Replace(values); } public void Synchronize(NotifyCollectionChangedEventArgs args) { if (args.Action == NotifyCollectionChangedAction.Add && args.NewItems != null) { AddRange(args.NewItems); } else if (args.Action == NotifyCollectionChangedAction.Remove && args.OldItems != null) { RemoveRange(args.OldItems); } else if (args.Action == NotifyCollectionChangedAction.Reset) { Clear(); } } protected override void OnPropertyChanged(PropertyChangedEventArgs e) { if (suppressChangedEvent) return; base.OnPropertyChanged(e); } protected override void OnCollectionChanged(NotifyCollectionChangedEventArgs e) { if (suppressChangedEvent) return; base.OnCollectionChanged(e); } } }