Search code examples
c#wpfsortingdatagridsortdirection

wpf set sorting programmatically, so that the header is toggled as sorted


I have a problem with a wpf toolkit DataGrid.

I have an ItemsSource with three columns:

FirstName

LastName

Address

In the C# codebehind I set the sort direction and which column to sort on like this:

ICollectionView view = CollectionViewSource.GetDefaultView(dataGrid1.ItemsSource);
view.SortDescriptions.Clear();
view.SortDescriptions.Add(new SortDescription("LastName", ListSortDirection.Ascending));
view.Refresh();

There is no problem in the actual sorting but there is in the headers visual style. If the user sorts a column by clicking on the header, the visual style changes, but the visual style does not indicate that the column sort description is set programmatically.

Why is this, and how can I toggle the header so it will show up as sorted?


Solution

  • I haven't tried it before, but I would think you could set the SortDirection property of the column.

                int columnIndex = 0;
                this.dataGrid1.ColumnFromDisplayIndex(columnIndex).SortDirection = 
                    ListSortDirection.Descending;