-
Notifications
You must be signed in to change notification settings - Fork 808
Expand file tree
/
Copy pathSortableObservableCollection.cs
More file actions
54 lines (44 loc) · 1.69 KB
/
SortableObservableCollection.cs
File metadata and controls
54 lines (44 loc) · 1.69 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
using System.Collections.ObjectModel;
using System.Collections.Specialized;
namespace UniGetUI.Core.Classes
{
/*
* An observable sorted collection that keeps IIndexableListItem indexes up to date
*/
public class SortableObservableCollection<T> : ObservableCollection<T> where T : IIndexableListItem
{
public Func<T, object>? SortingSelector { get; set; }
public bool Descending { get; set; }
public bool BlockSorting { get; set; }
protected override void OnCollectionChanged(NotifyCollectionChangedEventArgs e)
{
if (BlockSorting)
return;
base.OnCollectionChanged(e);
if (SortingSelector is null || e.Action is NotifyCollectionChangedAction.Remove or NotifyCollectionChangedAction.Reset)
return;
Sort();
}
public void Sort()
{
if (BlockSorting)
return;
BlockSorting = true;
if (SortingSelector is null)
{
throw new InvalidOperationException("SortableObservableCollection<T>.SortingSelector must not be null when sorting");
}
List<T> sorted = Descending ? this.OrderByDescending(SortingSelector).ToList() : this.OrderBy(SortingSelector).ToList();
foreach (T item in sorted)
{
Move(IndexOf(item), sorted.IndexOf(item));
}
for (int i = 0; i < Count; i++)
{
this.ElementAt(i).Index = i;
}
BlockSorting = false;
base.OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
}
}
}