How to change the first sort direction to WPF DataGridColumn

Right now (by default), when you click on a header on a custom sortable one DataGridColumn, it sorts it in ascending order on the first click and goes down on the second click.

How can I sort in descending order on the first click and ascending on the second click?

+5
source share
4 answers

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

myGrid.Sorting += (s, e) => e.Column.SortDirection = e.Column.SortDirection ?? ListSortDirection.Ascending;
+8
source

I did a similar thing in Winforms. Handle the DataGrid.Sorting event, then programmatically change the sort order if it is not "none".

Check this link for what it looks like in WinForms: Initial direction for sorting DataGridViewColumn

0
source

I think this is exactly what you were looking for ...

http://blogs.msdn.com/b/vinsibal/archive/2008/08/29/wpf-datagrid-tri-state-sorting-sample.aspx

In the blog above, they use another sorting state in the DataGrid ..

0
source

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

private void _myGrid_Sorting(object sender, DataGridSortingEventArgs e)
{
    if (e.Column.SortDirection == null)
        e.Column.SortDirection = ListSortDirection.Ascending;
}
0
source

All Articles