Avalonia Tip: Adding Cancel Sorting to DataGrid

Avalonia Tip: Adding Cancel Sorting to DataGrid

By default, clicking a column header only provides ascending and descending sorting, with no way to cancel

Last updated 7/17/2025 10:57 PM
沙漠尽头的狼
1 min read
Category
Avalonia UI
Tags
.NET C# Avalonia UI Interaction Design Avalonia

Requirement Background

By default, clicking a column header in a DataGrid toggles between ascending (↑) and descending (↓) sort order:

However, in practical business scenarios, users may need to quickly restore the default data sorting.

Implementation Solution

A method provided by a friendly colleague. If you have a better implementation, feel free to leave a comment:

public static class DataGridExtension
{
    public static void AddSorting(this Avalonia.Controls.DataGrid dataGrid)
    {
        var view = new DataGridCollectionView(dataGrid.ItemsSource);
        dataGrid.Sorting += (s, e) =>
        {
            if (s is not Avalonia.Controls.DataGrid) return;

            var memberPath = e.Column.SortMemberPath;
            var sortDescription = view.SortDescriptions.FirstOrDefault(d => d.PropertyPath == memberPath);
            if (sortDescription is not null && sortDescription.Direction == ListSortDirection.Descending)
            {
                view.SortDescriptions.Clear();
                e.Handled = true;
            }

            dataGrid.ItemsSource = view;
            view.Refresh();
        };
    }
}

Demo

This account continues to share practical tips on Avalonia. Welcome to follow, stay in touch, and make progress together.

Keep Exploring

Related Reading

More Articles