Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change first sort direction on WPF DataGridColumn

Tags:

wpf

datagrid

Right now (default) when you click a header on a user sortable DataGridColumn it sorts it ascending on first click and descending on second click.

How can I make it sort descending on first click and ascending on second click?

like image 220
Jon Erickson Avatar asked Jun 15 '12 00:06

Jon Erickson


2 Answers

I figured out a way to do it, not sure if it is the best way. But basically when the sorting event triggers and the current SortDirection is null I set it to Ascending so that the default sorter will reverse the SortDirection to descending, and this only happens on the first sort because that is the only time the SortDirection is null.

myGrid.Sorting += (s, e) => e.Column.SortDirection = e.Column.SortDirection ?? ListSortDirection.Ascending;
like image 79
Jon Erickson Avatar answered Nov 03 '22 11:11

Jon Erickson


Here's an expanded version of the accepted answer (I'm not a fan of that compact notation):

private void _myGrid_Sorting(object sender, DataGridSortingEventArgs e)
{
    if (e.Column.SortDirection == null)
        e.Column.SortDirection = ListSortDirection.Ascending;
}
like image 27
Eternal21 Avatar answered Nov 03 '22 12:11

Eternal21