Sort a wpf datagrid programmatically

voo’s solution was not working for me, ItemsSource was null, most likely because it was not directly set, but bound.
All other solutions I found here at StackOverflow were dealing with sorting the Model only, but the DataGrid header was not reflecting to the sort.

Here’s a proper solution based on the incomplete script here:

public static void SortDataGrid(DataGrid dataGrid, int columnIndex = 0, ListSortDirection sortDirection = ListSortDirection.Ascending)
    var column = dataGrid.Columns[columnIndex];

    // Clear current sort descriptions

    // Add the new sort description
    dataGrid.Items.SortDescriptions.Add(new SortDescription(column.SortMemberPath, sortDirection));

    // Apply sort
    foreach (var col in dataGrid.Columns)
        col.SortDirection = null;
    column.SortDirection = sortDirection;

    // Refresh items to display sort

In case of your code, it can be used like this:

SortDataGrid(myDataGridEvenements, 0, ListSortDirection.Ascending);

Or by using the default parameter values, simply:


Leave a Comment