Сортировка ObservableCollection в WPF
Чтобы сделать сортируемую наблюдаемую коллекцию в WPF, можно создать методы расширения для типа ObservableCollection:
Imports System.Collections.ObjectModel Imports System.Runtime.CompilerServices Module ObservableCollectionExtensions <Extension> Public Sub Sort(Of T)(ByRef collection As ObservableCollection(Of T), comparison As Comparison(Of T)) Dim sortableList = New List(Of T)(collection) sortableList.Sort(comparison) For i As Integer = 0 To sortableList.Count - 1 collection.Move(collection.IndexOf(sortableList(i)), i) Next End Sub <Extension> Public Sub Sort(Of T As IComparable)(ByRef collection As ObservableCollection(Of T)) If (collection.Count > 1) Then Dim sortableList As New List(Of T)(collection) Dim comp As Comparison(Of T) = Function(a, b) a.CompareTo(b) sortableList.Sort(comp) For i As Integer = 0 To sortableList.Count - 1 collection.Move(collection.IndexOf(sortableList(i)), i) Next End If End Sub End Module
Использование:
MyCollection.Sort(Function(a, b) a.CompareTo(b))
или просто:
MyCollection.Sort()
Ключевые слова: :