using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Data; /// /// Contains extension methods. /// public static class ObservableCollectionExtensions { private static object _syncLock = new object(); /// /// Replaces the specified old element with the specified new element. /// /// /// The observable collection. /// The old element. /// The new element. public static void Replace(this ObservableCollection collection, T oldElement, T newElement) { int index = collection.IndexOf(oldElement); collection.Remove(oldElement); collection.Insert(index, newElement); } /// /// Swaps the specified elements. /// /// /// The observable collection. /// Element1. /// Element2. public static void Swap(this ObservableCollection collection, T element1, T element2) { int index1 = collection.IndexOf(element1); int index2 = collection.IndexOf(element2); T tmp = collection[index1]; collection[index1] = collection[index2]; collection[index2] = tmp; } /// /// Removes the dragged element and inserts it after the dropped element position. /// /// /// The collection. /// The dragged element. /// The dropped element. public static void DragAndDrop(this ObservableCollection collection, T dragged, T dropped) { collection.Remove(dragged); collection.Insert(collection.IndexOf(dropped), dragged); } /// /// Enables cross thread operations on this collection. /// /// /// The collection. public static void EnableCrossThreadOperations(this ObservableCollection collection) { BindingOperations.EnableCollectionSynchronization(collection, _syncLock); } /// /// Creates a collection view from the observable collection. /// /// /// The collection. /// public static ICollectionView ToCollectionView(this ObservableCollection collection) { return CollectionViewSource.GetDefaultView(collection); } }