FruitBankHybridApp/FruitBank.Common/FastObservableCollection.cs

127 lines
3.6 KiB
C#

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<T>: IFastObservableCollection
{
public void Replace(IEnumerable<T> other);
public void Sort(IComparer<T> comparer);
public void SortAndReplace(IEnumerable<T> other, IComparer<T> comparer);
}
public class FastObservableCollection<T> : ObservableCollection<T>, IFastObservableCollection<T>
{
private bool suppressChangedEvent = false;
public void Replace(IEnumerable<T> 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<T> other, IComparer<T> comparer)
{
List<T> values = new(other);
values.Sort(comparer);
Replace(values);
}
public void Sort(IComparer<T> comparer)
{
List<T> 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);
}
}
}