CoreObservableCollection.cs 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742
  1. using System;
  2. using System.Collections;
  3. using System.Collections.ObjectModel;
  4. namespace InABox.Avalonia
  5. {
  6. // Licensed to the .NET Foundation under one or more agreements.
  7. // The .NET Foundation licenses this file to you under the MIT license.
  8. // See the LICENSE file in the project root for more information.
  9. using System.Collections.Generic;
  10. using System.Collections.Specialized;
  11. using System.ComponentModel;
  12. using System.Diagnostics;
  13. using System.Linq;
  14. /// <summary>
  15. /// Implementation of a dynamic data collection based on generic Collection&lt;T&gt;,
  16. /// implementing INotifyCollectionChanged to notify listeners
  17. /// when items get added, removed or the whole list is refreshed.
  18. ///
  19. /// Modified to Implement Cross-thread Synchronization of events
  20. /// Will trigger event callbacks on creating, rather than current thread.
  21. /// Collections should be created on Msin UI thread the to prevent exceptions
  22. /// </summary>
  23. public class CoreObservableCollection<T> : ObservableCollection<T>
  24. {
  25. //------------------------------------------------------
  26. //
  27. // Private Fields
  28. //
  29. //------------------------------------------------------
  30. #region Private Fields
  31. [NonSerialized] private DeferredEventsCollection? _deferredEvents;
  32. [NonSerialized] private SynchronizationContext? _synchronizationContext = SynchronizationContext.Current;
  33. #endregion Private Fields
  34. //------------------------------------------------------
  35. //
  36. // Constructors
  37. //
  38. //------------------------------------------------------
  39. #region Constructors
  40. /// <summary>
  41. /// Initializes a new instance of ObservableCollection that is empty and has default initial capacity.
  42. /// </summary>
  43. public CoreObservableCollection()
  44. {
  45. }
  46. /// <summary>
  47. /// Initializes a new instance of the ObservableCollection class that contains
  48. /// elements copied from the specified collection and has sufficient capacity
  49. /// to accommodate the number of elements copied.
  50. /// </summary>
  51. /// <param name="collection">The collection whose elements are copied to the new list.</param>
  52. /// <remarks>
  53. /// The elements are copied onto the ObservableCollection in the
  54. /// same order they are read by the enumerator of the collection.
  55. /// </remarks>
  56. /// <exception cref="ArgumentNullException"> collection is a null reference </exception>
  57. public CoreObservableCollection(IEnumerable<T> collection) : base(collection)
  58. {
  59. }
  60. /// <summary>
  61. /// Initializes a new instance of the ObservableCollection class
  62. /// that contains elements copied from the specified list
  63. /// </summary>
  64. /// <param name="list">The list whose elements are copied to the new list.</param>
  65. /// <remarks>
  66. /// The elements are copied onto the ObservableCollection in the
  67. /// same order they are read by the enumerator of the list.
  68. /// </remarks>
  69. /// <exception cref="ArgumentNullException"> list is a null reference </exception>
  70. public CoreObservableCollection(List<T> list) : base(list)
  71. {
  72. }
  73. #endregion Constructors
  74. //------------------------------------------------------
  75. //
  76. // Public Properties
  77. //
  78. //------------------------------------------------------
  79. #region Public Properties
  80. EqualityComparer<T>? _Comparer;
  81. public EqualityComparer<T> Comparer
  82. {
  83. get => _Comparer ??= EqualityComparer<T>.Default;
  84. private set => _Comparer = value;
  85. }
  86. /// <summary>
  87. /// Gets or sets a value indicating whether this collection acts as a <see cref="HashSet{T}"/>,
  88. /// disallowing duplicate items, based on <see cref="Comparer"/>.
  89. /// This might indeed consume background performance, but in the other hand,
  90. /// it will pay off in UI performance as less required UI updates are required.
  91. /// </summary>
  92. public bool AllowDuplicates { get; set; } = true;
  93. // If the collection is created on a non-UI thread, but needs to update the UI,
  94. // we should be able to set the UI context here to prevent exceptions
  95. public SynchronizationContext? SynchronizationContext
  96. {
  97. get => _synchronizationContext;
  98. set => _synchronizationContext = value;
  99. }
  100. #endregion Public Properties
  101. //------------------------------------------------------
  102. //
  103. // Public Methods
  104. //
  105. //------------------------------------------------------
  106. #region Public Methods
  107. /// <summary>
  108. /// Adds the elements of the specified collection to the end of the <see cref="ObservableCollection{T}"/>.
  109. /// </summary>
  110. /// <param name="collection">
  111. /// The collection whose elements should be added to the end of the <see cref="ObservableCollection{T}"/>.
  112. /// The collection itself cannot be null, but it can contain elements that are null, if type T is a reference type.
  113. /// </param>
  114. /// <exception cref="ArgumentNullException"><paramref name="collection"/> is null.</exception>
  115. public void AddRange(IEnumerable<T> collection)
  116. {
  117. InsertRange(Count, collection);
  118. }
  119. /// <summary>
  120. /// Inserts the elements of a collection into the <see cref="ObservableCollection{T}"/> at the specified index.
  121. /// </summary>
  122. /// <param name="index">The zero-based index at which the new elements should be inserted.</param>
  123. /// <param name="collection">The collection whose elements should be inserted into the List<T>.
  124. /// The collection itself cannot be null, but it can contain elements that are null, if type T is a reference type.</param>
  125. /// <exception cref="ArgumentNullException"><paramref name="collection"/> is null.</exception>
  126. /// <exception cref="ArgumentOutOfRangeException"><paramref name="index"/> is not in the collection range.</exception>
  127. public void InsertRange(int index, IEnumerable<T> collection)
  128. {
  129. if (collection == null)
  130. throw new ArgumentNullException(nameof(collection));
  131. if (index < 0)
  132. throw new ArgumentOutOfRangeException(nameof(index));
  133. if (index > Count)
  134. throw new ArgumentOutOfRangeException(nameof(index));
  135. if (!AllowDuplicates)
  136. collection =
  137. collection
  138. .Distinct(Comparer)
  139. .Where(item => !Items.Contains(item, Comparer))
  140. .ToList();
  141. if (collection is ICollection<T> countable)
  142. {
  143. if (countable.Count == 0)
  144. return;
  145. }
  146. else if (!collection.Any())
  147. return;
  148. CheckReentrancy();
  149. //expand the following couple of lines when adding more constructors.
  150. var target = (List<T>)Items;
  151. target.InsertRange(index, collection);
  152. OnEssentialPropertiesChanged();
  153. if (!(collection is IList list))
  154. list = new List<T>(collection);
  155. OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, list, index));
  156. }
  157. /// <summary>
  158. /// Removes the first occurence of each item in the specified collection from the <see cref="ObservableCollection{T}"/>.
  159. /// </summary>
  160. /// <param name="collection">The items to remove.</param>
  161. /// <exception cref="ArgumentNullException"><paramref name="collection"/> is null.</exception>
  162. public void RemoveRange(IEnumerable<T> collection)
  163. {
  164. if (collection == null)
  165. throw new ArgumentNullException(nameof(collection));
  166. if (Count == 0)
  167. return;
  168. else if (collection is ICollection<T> countable)
  169. {
  170. if (countable.Count == 0)
  171. return;
  172. else if (countable.Count == 1)
  173. using (IEnumerator<T> enumerator = countable.GetEnumerator())
  174. {
  175. enumerator.MoveNext();
  176. Remove(enumerator.Current);
  177. return;
  178. }
  179. }
  180. else if (!collection.Any())
  181. return;
  182. CheckReentrancy();
  183. var clusters = new Dictionary<int, List<T>>();
  184. var lastIndex = -1;
  185. List<T>? lastCluster = null;
  186. foreach (T item in collection)
  187. {
  188. var index = IndexOf(item);
  189. if (index < 0)
  190. continue;
  191. Items.RemoveAt(index);
  192. if (lastIndex == index && lastCluster != null)
  193. lastCluster.Add(item);
  194. else
  195. clusters[lastIndex = index] = lastCluster = new List<T> { item };
  196. }
  197. OnEssentialPropertiesChanged();
  198. if (Count == 0)
  199. OnCollectionReset();
  200. else
  201. foreach (KeyValuePair<int, List<T>> cluster in clusters)
  202. OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove,
  203. cluster.Value, cluster.Key));
  204. }
  205. /// <summary>
  206. /// Iterates over the collection and removes all items that satisfy the specified match.
  207. /// </summary>
  208. /// <remarks>The complexity is O(n).</remarks>
  209. /// <param name="match"></param>
  210. /// <returns>Returns the number of elements that where </returns>
  211. /// <exception cref="ArgumentNullException"><paramref name="match"/> is null.</exception>
  212. public int RemoveAll(Predicate<T> match)
  213. {
  214. return RemoveAll(0, Count, match);
  215. }
  216. /// <summary>
  217. /// Iterates over the specified range within the collection and removes all items that satisfy the specified match.
  218. /// </summary>
  219. /// <remarks>The complexity is O(n).</remarks>
  220. /// <param name="index">The index of where to start performing the search.</param>
  221. /// <param name="count">The number of items to iterate on.</param>
  222. /// <param name="match"></param>
  223. /// <returns>Returns the number of elements that where </returns>
  224. /// <exception cref="ArgumentOutOfRangeException"><paramref name="index"/> is out of range.</exception>
  225. /// <exception cref="ArgumentOutOfRangeException"><paramref name="count"/> is out of range.</exception>
  226. /// <exception cref="ArgumentNullException"><paramref name="match"/> is null.</exception>
  227. public int RemoveAll(int index, int count, Predicate<T> match)
  228. {
  229. if (index < 0)
  230. throw new ArgumentOutOfRangeException(nameof(index));
  231. if (count < 0)
  232. throw new ArgumentOutOfRangeException(nameof(count));
  233. if (index + count > Count)
  234. throw new ArgumentOutOfRangeException(nameof(index));
  235. if (match == null)
  236. throw new ArgumentNullException(nameof(match));
  237. if (Count == 0)
  238. return 0;
  239. List<T>? cluster = null;
  240. var clusterIndex = -1;
  241. var removedCount = 0;
  242. using (BlockReentrancy())
  243. using (DeferEvents())
  244. {
  245. for (var i = 0; i < count; i++, index++)
  246. {
  247. T item = Items[index];
  248. if (match(item))
  249. {
  250. Items.RemoveAt(index);
  251. removedCount++;
  252. if (clusterIndex == index)
  253. {
  254. Debug.Assert(cluster != null);
  255. cluster!.Add(item);
  256. }
  257. else
  258. {
  259. cluster = new List<T> { item };
  260. clusterIndex = index;
  261. }
  262. index--;
  263. }
  264. else if (clusterIndex > -1)
  265. {
  266. OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove,
  267. cluster, clusterIndex));
  268. clusterIndex = -1;
  269. cluster = null;
  270. }
  271. }
  272. if (clusterIndex > -1)
  273. OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove,
  274. cluster, clusterIndex));
  275. }
  276. if (removedCount > 0)
  277. OnEssentialPropertiesChanged();
  278. return removedCount;
  279. }
  280. /// <summary>
  281. /// Removes a range of elements from the <see cref="ObservableCollection{T}"/>>.
  282. /// </summary>
  283. /// <param name="index">The zero-based starting index of the range of elements to remove.</param>
  284. /// <param name="count">The number of elements to remove.</param>
  285. /// <exception cref="ArgumentOutOfRangeException">The specified range is exceeding the collection.</exception>
  286. public void RemoveRange(int index, int count)
  287. {
  288. if (index < 0)
  289. throw new ArgumentOutOfRangeException(nameof(index));
  290. if (count < 0)
  291. throw new ArgumentOutOfRangeException(nameof(count));
  292. if (index + count > Count)
  293. throw new ArgumentOutOfRangeException(nameof(index));
  294. if (count == 0)
  295. return;
  296. if (count == 1)
  297. {
  298. RemoveItem(index);
  299. return;
  300. }
  301. //Items will always be List<T>, see constructors
  302. var items = (List<T>)Items;
  303. List<T> removedItems = items.GetRange(index, count);
  304. CheckReentrancy();
  305. items.RemoveRange(index, count);
  306. OnEssentialPropertiesChanged();
  307. if (Count == 0)
  308. OnCollectionReset();
  309. else
  310. OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove,
  311. removedItems, index));
  312. }
  313. /// <summary>
  314. /// Clears the current collection and replaces it with the specified collection,
  315. /// using <see cref="Comparer"/>.
  316. /// </summary>
  317. /// <param name="collection">The items to fill the collection with, after clearing it.</param>
  318. /// <exception cref="ArgumentNullException"><paramref name="collection"/> is null.</exception>
  319. public void ReplaceRange(IEnumerable<T> collection)
  320. {
  321. ReplaceRange(0, Count, collection);
  322. }
  323. /// <summary>
  324. /// Removes the specified range and inserts the specified collection in its position, leaving equal items in equal positions intact.
  325. /// </summary>
  326. /// <param name="index">The index of where to start the replacement.</param>
  327. /// <param name="count">The number of items to be replaced.</param>
  328. /// <param name="collection">The collection to insert in that location.</param>
  329. /// <exception cref="ArgumentOutOfRangeException"><paramref name="index"/> is out of range.</exception>
  330. /// <exception cref="ArgumentOutOfRangeException"><paramref name="count"/> is out of range.</exception>
  331. /// <exception cref="ArgumentNullException"><paramref name="collection"/> is null.</exception>
  332. /// <exception cref="ArgumentNullException"><paramref name="comparer"/> is null.</exception>
  333. public void ReplaceRange(int index, int count, IEnumerable<T> collection)
  334. {
  335. if (index < 0)
  336. throw new ArgumentOutOfRangeException(nameof(index));
  337. if (count < 0)
  338. throw new ArgumentOutOfRangeException(nameof(count));
  339. if (index + count > Count)
  340. throw new ArgumentOutOfRangeException(nameof(index));
  341. if (collection == null)
  342. throw new ArgumentNullException(nameof(collection));
  343. if (!AllowDuplicates)
  344. collection =
  345. collection
  346. .Distinct(Comparer)
  347. .ToList();
  348. if (collection is ICollection<T> countable)
  349. {
  350. if (countable.Count == 0)
  351. {
  352. RemoveRange(index, count);
  353. return;
  354. }
  355. }
  356. else if (!collection.Any())
  357. {
  358. RemoveRange(index, count);
  359. return;
  360. }
  361. if (index + count == 0)
  362. {
  363. InsertRange(0, collection);
  364. return;
  365. }
  366. if (!(collection is IList<T> list))
  367. list = new List<T>(collection);
  368. using (BlockReentrancy())
  369. using (DeferEvents())
  370. {
  371. var rangeCount = index + count;
  372. var addedCount = list.Count;
  373. var changesMade = false;
  374. List<T>?
  375. newCluster = null,
  376. oldCluster = null;
  377. int i = index;
  378. for (; i < rangeCount && i - index < addedCount; i++)
  379. {
  380. //parallel position
  381. T old = this[i], @new = list[i - index];
  382. if (Comparer.Equals(old, @new))
  383. {
  384. OnRangeReplaced(i, newCluster!, oldCluster!);
  385. continue;
  386. }
  387. else
  388. {
  389. Items[i] = @new;
  390. if (newCluster == null)
  391. {
  392. Debug.Assert(oldCluster == null);
  393. newCluster = new List<T> { @new };
  394. oldCluster = new List<T> { old };
  395. }
  396. else
  397. {
  398. newCluster.Add(@new);
  399. oldCluster!.Add(old);
  400. }
  401. changesMade = true;
  402. }
  403. }
  404. OnRangeReplaced(i, newCluster!, oldCluster!);
  405. //exceeding position
  406. if (count != addedCount)
  407. {
  408. var items = (List<T>)Items;
  409. if (count > addedCount)
  410. {
  411. var removedCount = rangeCount - addedCount;
  412. T[] removed = new T[removedCount];
  413. items.CopyTo(i, removed, 0, removed.Length);
  414. items.RemoveRange(i, removedCount);
  415. OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove,
  416. removed, i));
  417. }
  418. else
  419. {
  420. var k = i - index;
  421. T[] added = new T[addedCount - k];
  422. for (int j = k; j < addedCount; j++)
  423. {
  424. T @new = list[j];
  425. added[j - k] = @new;
  426. }
  427. items.InsertRange(i, added);
  428. OnCollectionChanged(
  429. new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, added, i));
  430. }
  431. OnEssentialPropertiesChanged();
  432. }
  433. else if (changesMade)
  434. {
  435. OnIndexerPropertyChanged();
  436. }
  437. }
  438. }
  439. #endregion Public Methods
  440. //------------------------------------------------------
  441. //
  442. // Protected Methods
  443. //
  444. //------------------------------------------------------
  445. #region Protected Methods
  446. /// <summary>
  447. /// Called by base class Collection&lt;T&gt; when the list is being cleared;
  448. /// raises a CollectionChanged event to any listeners.
  449. /// </summary>
  450. protected override void ClearItems()
  451. {
  452. if (Count == 0)
  453. return;
  454. CheckReentrancy();
  455. base.ClearItems();
  456. OnEssentialPropertiesChanged();
  457. OnCollectionReset();
  458. }
  459. /// <inheritdoc/>
  460. protected override void InsertItem(int index, T item)
  461. {
  462. if (!AllowDuplicates && Items.Contains(item))
  463. return;
  464. base.InsertItem(index, item);
  465. }
  466. /// <inheritdoc/>
  467. protected override void SetItem(int index, T item)
  468. {
  469. if (AllowDuplicates)
  470. {
  471. if (Comparer.Equals(this[index], item))
  472. return;
  473. }
  474. else if (Items.Contains(item, Comparer))
  475. return;
  476. CheckReentrancy();
  477. T oldItem = this[index];
  478. base.SetItem(index, item);
  479. OnIndexerPropertyChanged();
  480. OnCollectionChanged(NotifyCollectionChangedAction.Replace, oldItem!, item!, index);
  481. }
  482. /// <summary>
  483. /// Raise CollectionChanged event to any listeners.
  484. /// Properties/methods modifying this ObservableCollection will raise
  485. /// a collection changed event through this virtual method.
  486. /// </summary>
  487. /// <remarks>
  488. /// When overriding this method, either call its base implementation
  489. /// or call <see cref="BlockReentrancy"/> to guard against reentrant collection changes.
  490. /// </remarks>
  491. protected override void OnCollectionChanged(NotifyCollectionChangedEventArgs e)
  492. {
  493. if (_synchronizationContext == null || SynchronizationContext.Current == _synchronizationContext)
  494. {
  495. // Execute the CollectionChanged event on the current thread
  496. RaiseCollectionChanged(e);
  497. }
  498. else
  499. {
  500. // Raises the CollectionChanged event on the creator thread
  501. _synchronizationContext.Send(RaiseCollectionChanged, e);
  502. }
  503. }
  504. private void RaiseCollectionChanged(object? param)
  505. {
  506. // We are in the creator thread, call the base implementation directly
  507. if (param is NotifyCollectionChangedEventArgs args)
  508. {
  509. if (_deferredEvents != null)
  510. {
  511. _deferredEvents.Add(args);
  512. return;
  513. }
  514. base.OnCollectionChanged(args);
  515. }
  516. }
  517. protected virtual IDisposable DeferEvents() => new DeferredEventsCollection(this);
  518. #endregion Protected Methods
  519. //------------------------------------------------------
  520. //
  521. // Private Methods
  522. //
  523. //------------------------------------------------------
  524. #region Private Methods
  525. /// <summary>
  526. /// Helper to raise Count property and the Indexer property.
  527. /// </summary>
  528. void OnEssentialPropertiesChanged()
  529. {
  530. OnPropertyChanged(EventArgsCache.CountPropertyChanged);
  531. OnIndexerPropertyChanged();
  532. }
  533. /// <summary>
  534. /// /// Helper to raise a PropertyChanged event for the Indexer property
  535. /// /// </summary>
  536. void OnIndexerPropertyChanged() =>
  537. OnPropertyChanged(EventArgsCache.IndexerPropertyChanged);
  538. protected override void OnPropertyChanged(PropertyChangedEventArgs e)
  539. {
  540. if (_synchronizationContext == null || SynchronizationContext.Current == _synchronizationContext)
  541. {
  542. // Execute the PropertyChanged event on the current thread
  543. RaisePropertyChanged(e);
  544. }
  545. else
  546. {
  547. // Raises the PropertyChanged event on the creator thread
  548. _synchronizationContext.Send(RaisePropertyChanged, e);
  549. }
  550. }
  551. private void RaisePropertyChanged(object? param)
  552. {
  553. // We are in the creator thread, call the base implementation directly
  554. if (param is PropertyChangedEventArgs args)
  555. base.OnPropertyChanged(args);
  556. }
  557. /// <summary>
  558. /// Helper to raise CollectionChanged event to any listeners
  559. /// </summary>
  560. void OnCollectionChanged(NotifyCollectionChangedAction action, object oldItem, object newItem, int index) =>
  561. OnCollectionChanged(new NotifyCollectionChangedEventArgs(action, newItem, oldItem, index));
  562. /// <summary>
  563. /// Helper to raise CollectionChanged event with action == Reset to any listeners
  564. /// </summary>
  565. void OnCollectionReset() =>
  566. OnCollectionChanged(EventArgsCache.ResetCollectionChanged);
  567. /// <summary>
  568. /// Helper to raise event for clustered action and clear cluster.
  569. /// </summary>
  570. /// <param name="followingItemIndex">The index of the item following the replacement block.</param>
  571. /// <param name="newCluster"></param>
  572. /// <param name="oldCluster"></param>
  573. //TODO should have really been a local method inside ReplaceRange(int index, int count, IEnumerable<T> collection, IEqualityComparer<T> comparer),
  574. //move when supported language version updated.
  575. void OnRangeReplaced(int followingItemIndex, ICollection<T> newCluster, ICollection<T> oldCluster)
  576. {
  577. if (oldCluster == null || oldCluster.Count == 0)
  578. {
  579. Debug.Assert(newCluster == null || newCluster.Count == 0);
  580. return;
  581. }
  582. OnCollectionChanged(
  583. new NotifyCollectionChangedEventArgs(
  584. NotifyCollectionChangedAction.Replace,
  585. new List<T>(newCluster),
  586. new List<T>(oldCluster),
  587. followingItemIndex - oldCluster.Count));
  588. oldCluster.Clear();
  589. newCluster.Clear();
  590. }
  591. #endregion Private Methods
  592. //------------------------------------------------------
  593. //
  594. // Private Types
  595. //
  596. //------------------------------------------------------
  597. #region Private Types
  598. sealed class DeferredEventsCollection : List<NotifyCollectionChangedEventArgs>, IDisposable
  599. {
  600. readonly CoreObservableCollection<T> _collection;
  601. public DeferredEventsCollection(CoreObservableCollection<T> collection)
  602. {
  603. Debug.Assert(collection != null);
  604. Debug.Assert(collection._deferredEvents == null);
  605. _collection = collection;
  606. _collection._deferredEvents = this;
  607. }
  608. public void Dispose()
  609. {
  610. _collection._deferredEvents = null;
  611. foreach (var args in this)
  612. _collection.OnCollectionChanged(args);
  613. }
  614. }
  615. #endregion Private Types
  616. }
  617. /// <remarks>
  618. /// To be kept outside <see cref="ObservableCollection{T}"/>, since otherwise, a new instance will be created for each generic type used.
  619. /// </remarks>
  620. internal static class EventArgsCache
  621. {
  622. internal static readonly PropertyChangedEventArgs CountPropertyChanged = new PropertyChangedEventArgs("Count");
  623. internal static readonly PropertyChangedEventArgs IndexerPropertyChanged =
  624. new PropertyChangedEventArgs("Item[]");
  625. internal static readonly NotifyCollectionChangedEventArgs ResetCollectionChanged =
  626. new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset);
  627. }
  628. }