ManualObservableCollection`1.cs 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Collections.ObjectModel;
  4. using System.Collections.Specialized;
  5. using System.ComponentModel;
  6. namespace HandyControl.Collections;
  7. [Serializable]
  8. public class ManualObservableCollection<T> : ObservableCollection<T>
  9. {
  10. private const string CountString = "Count";
  11. private const string IndexerName = "Item[]";
  12. private int _oldCount;
  13. private bool _canNotify = true;
  14. public bool CanNotify
  15. {
  16. get => _canNotify;
  17. set
  18. {
  19. _canNotify = value;
  20. if (value)
  21. {
  22. if (_oldCount != Count)
  23. {
  24. OnPropertyChanged(new PropertyChangedEventArgs(CountString));
  25. }
  26. OnPropertyChanged(new PropertyChangedEventArgs(IndexerName));
  27. OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
  28. }
  29. else
  30. {
  31. _oldCount = Count;
  32. }
  33. }
  34. }
  35. public ManualObservableCollection()
  36. {
  37. }
  38. public ManualObservableCollection(List<T> list) : base(list != null ? new List<T>(list.Count) : list) => CopyFrom(list);
  39. public ManualObservableCollection(IEnumerable<T> collection)
  40. {
  41. if (collection == null) throw new ArgumentNullException(nameof(collection));
  42. CopyFrom(collection);
  43. }
  44. protected override void OnPropertyChanged(PropertyChangedEventArgs e)
  45. {
  46. if (!CanNotify) return;
  47. base.OnPropertyChanged(e);
  48. }
  49. protected override void OnCollectionChanged(NotifyCollectionChangedEventArgs e)
  50. {
  51. if (!CanNotify) return;
  52. base.OnCollectionChanged(e);
  53. }
  54. private void CopyFrom(IEnumerable<T> collection)
  55. {
  56. var items = Items;
  57. if (collection != null)
  58. {
  59. using var enumerator = collection.GetEnumerator();
  60. while (enumerator.MoveNext())
  61. {
  62. items.Add(enumerator.Current);
  63. }
  64. }
  65. }
  66. }