1
+ using System . Windows . Controls . Primitives ;
2
+ using FoliCon . Modules . utils ;
3
+
4
+ namespace FoliCon . Modules . UI ;
5
+
6
+ public class ListViewClickSortBehavior : Behavior < ListView >
7
+ {
8
+ private GridViewColumnHeader _lastHeaderClicked ;
9
+ private ListSortDirection _lastDirection = ListSortDirection . Ascending ;
10
+
11
+ protected override void OnAttached ( )
12
+ {
13
+ base . OnAttached ( ) ;
14
+
15
+ AssociatedObject . AddHandler ( ButtonBase . ClickEvent , new RoutedEventHandler ( OnClick ) ) ;
16
+ ( ( INotifyCollectionChanged ) AssociatedObject . Items ) . CollectionChanged += ListView_CollectionChanged ;
17
+ }
18
+
19
+ protected override void OnDetaching ( )
20
+ {
21
+ base . OnDetaching ( ) ;
22
+
23
+ AssociatedObject . RemoveHandler ( ButtonBase . ClickEvent , new RoutedEventHandler ( OnClick ) ) ;
24
+ ( ( INotifyCollectionChanged ) AssociatedObject . Items ) . CollectionChanged -= ListView_CollectionChanged ;
25
+ }
26
+
27
+ private void ListView_CollectionChanged ( object sender , NotifyCollectionChangedEventArgs e )
28
+ {
29
+ if ( e . Action == NotifyCollectionChangedAction . Reset )
30
+ {
31
+ UiUtils . SetColumnWidth ( AssociatedObject ) ;
32
+ }
33
+ }
34
+
35
+ private void OnClick ( object sender , RoutedEventArgs e )
36
+ {
37
+ if ( e . OriginalSource is not GridViewColumnHeader headerClicked ) return ;
38
+ if ( headerClicked . Role == GridViewColumnHeaderRole . Padding ) return ;
39
+
40
+ ListSortDirection direction ;
41
+ if ( headerClicked != _lastHeaderClicked )
42
+ {
43
+ direction = ListSortDirection . Ascending ;
44
+ }
45
+ else
46
+ {
47
+ direction = _lastDirection == ListSortDirection . Ascending
48
+ ? ListSortDirection . Descending
49
+ : ListSortDirection . Ascending ;
50
+ }
51
+
52
+ var header = headerClicked . Column . Header as string ;
53
+ Sort ( header , direction ) ;
54
+
55
+ headerClicked . Column . HeaderTemplate = direction == ListSortDirection . Ascending
56
+ ? Application . Current . Resources [ "HeaderTemplateArrowUp" ] as DataTemplate
57
+ : Application . Current . Resources [ "HeaderTemplateArrowDown" ] as DataTemplate ;
58
+
59
+ // Remove arrow from previously sorted header
60
+ if ( _lastHeaderClicked != null && _lastHeaderClicked != headerClicked )
61
+ {
62
+ _lastHeaderClicked . Column . HeaderTemplate = null ;
63
+ }
64
+
65
+ _lastHeaderClicked = headerClicked ;
66
+ _lastDirection = direction ;
67
+ }
68
+
69
+ private void Sort ( string sortBy , ListSortDirection direction )
70
+ {
71
+ var dataView = CollectionViewSource . GetDefaultView ( AssociatedObject . ItemsSource ) ;
72
+ dataView . SortDescriptions . Clear ( ) ;
73
+ var sd = new SortDescription ( sortBy , direction ) ;
74
+ dataView . SortDescriptions . Add ( sd ) ;
75
+ dataView . Refresh ( ) ;
76
+ }
77
+ }
0 commit comments