I have a DataGrid in WPF app with several columns, including a Name column. If the users switches to a particular view, I want the data to be pre-sorted by Name
This works for me.
ListSortDirection sortDirection;
int selectedColumnIndex;
private void customerDataGrid_Sorting(object sender, DataGridSortingEventArgs e)
{
selectedColumnIndex = e.Column.DisplayIndex;
sortDirection = (e.Column.SortDirection == ListSortDirection.Ascending ? ListSortDirection.Descending: ListSortDirection.Ascending);
}
private void applySortDescriptions(ListSortDirection listSortDirection)
{
//Clear current sort descriptions
customerDataGrid.Items.SortDescriptions.Clear();
//Get property name to apply sort based on desired column
string propertyName = customerDataGrid.Columns[selectedColumnIndex].SortMemberPath;
//Add the new sort description
customerDataGrid.Items.SortDescriptions.Add(new SortDescription(propertyName, listSortDirection));
//apply sort
applySortDirection(listSortDirection);
//refresh items to display sort
customerDataGrid.Items.Refresh();
}
private void applySortDirection(ListSortDirection listSortDirection)
{
customerDataGrid.Columns[selectedColumnIndex].SortDirection = listSortDirection;
}