5
votes

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?

4

4 Answers

8
votes

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;
1
votes

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;
}
0
votes

I've done a similar thing in Winforms. Handle the DataGrid.Sorting event, then programatically reverse the sort order if it is not "none".

Check this link for what this looks like in WinForms: DataGridViewColumn initial sort direction

0
votes

I think this is the way that you were looking for...

https://docs.microsoft.com/en-us/archive/blogs/vinsibal/wpf-datagrid-tri-state-sorting-sample

In the above blog they use one more state of Sorting in DataGrid..