ObservableDictionary.cs 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176
  1. using System.Collections;
  2. using System.Collections.Concurrent;
  3. using System.Collections.Generic;
  4. using System.Collections.Specialized;
  5. using System.ComponentModel;
  6. using System.Threading;
  7. namespace InABox.Core
  8. {
  9. public class ObservableDictionary<TKey, TValue> :
  10. ICollection<KeyValuePair<TKey, TValue>>, IDictionary<TKey, TValue>,
  11. INotifyCollectionChanged, INotifyPropertyChanged
  12. {
  13. private readonly SynchronizationContext _context;
  14. private readonly ConcurrentDictionary<TKey, TValue> _dictionary;
  15. /// <summary>
  16. /// Initializes an instance of the ObservableConcurrentDictionary class.
  17. /// </summary>
  18. public ObservableDictionary()
  19. {
  20. _context = AsyncOperationManager.SynchronizationContext;
  21. _dictionary = new ConcurrentDictionary<TKey, TValue>();
  22. }
  23. /// <summary>Event raised when the collection changes.</summary>
  24. public event NotifyCollectionChangedEventHandler CollectionChanged;
  25. /// <summary>Event raised when a property on the collection changes.</summary>
  26. public event PropertyChangedEventHandler PropertyChanged;
  27. /// <summary>
  28. /// Notifies observers of CollectionChanged or PropertyChanged of an update to the dictionary.
  29. /// </summary>
  30. private void NotifyObserversOfChange()
  31. {
  32. var collectionHandler = CollectionChanged;
  33. var propertyHandler = PropertyChanged;
  34. if (collectionHandler != null || propertyHandler != null)
  35. _context.Post(s =>
  36. {
  37. if (collectionHandler != null) collectionHandler(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
  38. if (propertyHandler != null)
  39. {
  40. propertyHandler(this, new PropertyChangedEventArgs("Count"));
  41. propertyHandler(this, new PropertyChangedEventArgs("Keys"));
  42. propertyHandler(this, new PropertyChangedEventArgs("Values"));
  43. }
  44. }, null);
  45. }
  46. /// <summary>Attempts to add an item to the dictionary, notifying observers of any changes.</summary>
  47. /// <param name="item">The item to be added.</param>
  48. /// <returns>Whether the add was successful.</returns>
  49. private bool TryAddWithNotification(KeyValuePair<TKey, TValue> item)
  50. {
  51. return TryAddWithNotification(item.Key, item.Value);
  52. }
  53. /// <summary>Attempts to add an item to the dictionary, notifying observers of any changes.</summary>
  54. /// <param name="key">The key of the item to be added.</param>
  55. /// <param name="value">The value of the item to be added.</param>
  56. /// <returns>Whether the add was successful.</returns>
  57. private bool TryAddWithNotification(TKey key, TValue value)
  58. {
  59. var result = _dictionary.TryAdd(key, value);
  60. if (result) NotifyObserversOfChange();
  61. return result;
  62. }
  63. /// <summary>Attempts to remove an item from the dictionary, notifying observers of any changes.</summary>
  64. /// <param name="key">The key of the item to be removed.</param>
  65. /// <param name="value">The value of the item removed.</param>
  66. /// <returns>Whether the removal was successful.</returns>
  67. private bool TryRemoveWithNotification(TKey key, out TValue value)
  68. {
  69. var result = _dictionary.TryRemove(key, out value);
  70. if (result) NotifyObserversOfChange();
  71. return result;
  72. }
  73. /// <summary>Attempts to add or update an item in the dictionary, notifying observers of any changes.</summary>
  74. /// <param name="key">The key of the item to be updated.</param>
  75. /// <param name="value">The new value to set for the item.</param>
  76. /// <returns>Whether the update was successful.</returns>
  77. private void UpdateWithNotification(TKey key, TValue value)
  78. {
  79. _dictionary[key] = value;
  80. NotifyObserversOfChange();
  81. }
  82. #region ICollection<KeyValuePair<TKey,TValue>> Members
  83. void ICollection<KeyValuePair<TKey, TValue>>.Add(KeyValuePair<TKey, TValue> item)
  84. {
  85. TryAddWithNotification(item);
  86. }
  87. void ICollection<KeyValuePair<TKey, TValue>>.Clear()
  88. {
  89. ((ICollection<KeyValuePair<TKey, TValue>>)_dictionary).Clear();
  90. NotifyObserversOfChange();
  91. }
  92. bool ICollection<KeyValuePair<TKey, TValue>>.Contains(KeyValuePair<TKey, TValue> item)
  93. {
  94. return ((ICollection<KeyValuePair<TKey, TValue>>)_dictionary).Contains(item);
  95. }
  96. void ICollection<KeyValuePair<TKey, TValue>>.CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex)
  97. {
  98. ((ICollection<KeyValuePair<TKey, TValue>>)_dictionary).CopyTo(array, arrayIndex);
  99. }
  100. int ICollection<KeyValuePair<TKey, TValue>>.Count => ((ICollection<KeyValuePair<TKey, TValue>>)_dictionary).Count;
  101. bool ICollection<KeyValuePair<TKey, TValue>>.IsReadOnly => ((ICollection<KeyValuePair<TKey, TValue>>)_dictionary).IsReadOnly;
  102. bool ICollection<KeyValuePair<TKey, TValue>>.Remove(KeyValuePair<TKey, TValue> item)
  103. {
  104. TValue temp;
  105. return TryRemoveWithNotification(item.Key, out temp);
  106. }
  107. #endregion
  108. #region IEnumerable<KeyValuePair<TKey,TValue>> Members
  109. IEnumerator<KeyValuePair<TKey, TValue>> IEnumerable<KeyValuePair<TKey, TValue>>.GetEnumerator()
  110. {
  111. return ((ICollection<KeyValuePair<TKey, TValue>>)_dictionary).GetEnumerator();
  112. }
  113. IEnumerator IEnumerable.GetEnumerator()
  114. {
  115. return ((ICollection<KeyValuePair<TKey, TValue>>)_dictionary).GetEnumerator();
  116. }
  117. #endregion
  118. #region IDictionary<TKey,TValue> Members
  119. public void Add(TKey key, TValue value)
  120. {
  121. TryAddWithNotification(key, value);
  122. }
  123. public bool ContainsKey(TKey key)
  124. {
  125. return _dictionary.ContainsKey(key);
  126. }
  127. public ICollection<TKey> Keys => _dictionary.Keys;
  128. public bool Remove(TKey key)
  129. {
  130. TValue temp;
  131. return TryRemoveWithNotification(key, out temp);
  132. }
  133. public bool TryGetValue(TKey key, out TValue value)
  134. {
  135. return _dictionary.TryGetValue(key, out value);
  136. }
  137. public ICollection<TValue> Values => _dictionary.Values;
  138. public TValue this[TKey key]
  139. {
  140. get => _dictionary[key];
  141. set => UpdateWithNotification(key, value);
  142. }
  143. #endregion
  144. }
  145. }