Articles in this section
Category / Section

How to sort multiple column without pressing Ctrl key in WPF DataGrid (SfDataGrid)?

4 mins read

WPF DataGrid (SfDataGrid) allows you to perform the multiple sorting without pressing the Ctrl Key. You can achieve this by using the SortColumnsChanging event which will be raised while clicking on the column header. You should cancel the current sorting process and need to add the new sort column to SorColumnDescriptions using a Dispatcher.

In WPF

void SfdataGrid_SortColumnsChanging(object sender, GridSortColumnsChangingEventArgs e)
{
    e.Cancel = true;
    if (e.Action == System.Collections.Specialized.NotifyCollectionChangedAction.Add)
    {
        this.SfdataGrid.Dispatcher.BeginInvoke(new Action(() =>
        {
            this.SfdataGrid.SortColumnDescriptions.Add(e.AddedItems[0]);
        }), DispatcherPriority.ApplicationIdle);
 
    }
    else if (e.Action == System.Collections.Specialized.NotifyCollectionChangedAction.Replace)
    {
        this.SfdataGrid.Dispatcher.BeginInvoke(new Action(() =>
        {
            var sordesc = this.SfdataGrid.SortColumnDescriptions.FirstOrDefault(sd => sd.ColumnName == e.AddedItems[0].ColumnName);
            this.SfdataGrid.SortColumnDescriptions.Remove(sordesc);
            this.SfdataGrid.SortColumnDescriptions.Add(e.AddedItems[0]);
        }), DispatcherPriority.ApplicationIdle);
 
    }
}

 

In UWP

private async void SfdataGrid_SortColumnsChanging(object sender, Syncfusion.UI.Xaml.Grid.GridSortColumnsChangingEventArgs e)
{
    e.Cancel = true;
    if (e.Action == System.Collections.Specialized.NotifyCollectionChangedAction.Add)
    {
        await this.SfdataGrid.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
        {
            this.SfdataGrid.SortColumnDescriptions.Add(e.AddedItems[0]);
        });
    }
    else if (e.Action == System.Collections.Specialized.NotifyCollectionChangedAction.Replace)
    {
        await this.SfdataGrid.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
        {
            var sordesc = this.SfdataGrid.SortColumnDescriptions.FirstOrDefault(sd => sd.ColumnName == e.AddedItems[0].ColumnName);
            this.SfdataGrid.SortColumnDescriptions.Remove(sordesc);
            this.SfdataGrid.SortColumnDescriptions.Add(e.AddedItems[0]);
        });
    }
}

 

Applied sorting to multiple columns in WPF DataGrid

View WPF DataGrid Sorting Demo in GitHub.

Did you find this information helpful?
Yes
No
Help us improve this page
Please provide feedback or comments
Comments (0)
Please  to leave a comment
Access denied
Access denied