Jon Erickson
Jon Erickson

Reputation: 114846

How to change first sort direction on WPF DataGridColumn

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?

Upvotes: 5

Views: 3928

Answers (4)

David Bekham
David Bekham

Reputation: 2175

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

https://learn.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..

Upvotes: 0

Eternal21
Eternal21

Reputation: 4664

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

Upvotes: 1

Jon Erickson
Jon Erickson

Reputation: 114846

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;

Upvotes: 8

Steve Konves
Steve Konves

Reputation: 2668

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

Upvotes: 0

Related Questions