-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathDataGrid.cs
110 lines (88 loc) · 3.43 KB
/
DataGrid.cs
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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
/*
* Written by Ronnie Overby
* and part of the Ronnie Overby Grab Bag: https://github.com/ronnieoverby/RonnieOverbyGrabBag
*/
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Windows.Controls;
using System.Windows.Input;
namespace Overby.WPF.Controls
{
public class DataGrid : System.Windows.Controls.DataGrid
{
public DataGrid()
{
SortDescriptions = new List<SortDescription>();
Sorting += DataGridSorting;
}
protected List<SortDescription> SortDescriptions { get; private set; }
public event EventHandler<SortConstructedEventArgs> SortConstructed;
public void OnSortConstructed(SortConstructedEventArgs e)
{
var handler = SortConstructed;
if (handler != null) handler(this, e);
}
private void DataGridSorting(object sender, DataGridSortingEventArgs e)
{
e.Handled = true;
e.Column.SortDirection = e.Column.SortDirection != ListSortDirection.Ascending
? ListSortDirection.Ascending
: ListSortDirection.Descending;
var sd = new SortDescription(e.Column.SortMemberPath, e.Column.SortDirection.Value);
if (ShiftPressed)
SortDescriptions =
SortDescriptions.Where(x => x.PropertyName != sd.PropertyName).ToList();
else
SortDescriptions.Clear();
SortDescriptions.Add(sd);
OnSortConstructed(new SortConstructedEventArgs(SortDescriptions));
}
private bool ShiftPressed
{
get { return (Keyboard.Modifiers & ModifierKeys.Shift) == ModifierKeys.Shift; }
}
}
public class SortConstructedEventArgs : EventArgs
{
public List<SortDescription> SortDescriptions { get; private set; }
public SortConstructedEventArgs(List<SortDescription> sortStack)
{
SortDescriptions = sortStack;
}
public IOrderedQueryable<T> Order<T>(IQueryable<T> queryable)
{
if (SortDescriptions == null || SortDescriptions.Count == 0)
return queryable.OrderBy(x => 0);
IOrderedQueryable<T> result;
var first = SortDescriptions.First();
switch (first.Direction)
{
case ListSortDirection.Ascending:
result = queryable.OrderBy(first.PropertyName); // uses orderby extension methods!
break;
case ListSortDirection.Descending:
result = queryable.OrderByDescending(first.PropertyName);
break;
default:
throw new ArgumentOutOfRangeException();
}
foreach (var sort in SortDescriptions.Skip(1))
{
switch (sort.Direction)
{
case ListSortDirection.Ascending:
result = result.ThenBy(sort.PropertyName);
break;
case ListSortDirection.Descending:
result = result.ThenByDescending(sort.PropertyName);
break;
default:
throw new ArgumentOutOfRangeException();
}
}
return result;
}
}
}