Avalonia Tips: Add and Unsort DataGrid

Avalonia Tips: Add and Unsort DataGrid

By default, clicking column headers can only be sorted in ascending and descending order, and cannot be cancelled

最后更新 7/17/2025 10:57 PM
沙漠尽头的狼
预计阅读 1 分钟
分类
Avalonia UI
标签
.NET C# Avalonia UI interaction design Avalonia

Demand background

By default, DataGrid can only switch between ascending (↑) and descending (↓) states by clicking on the column header:

However, in actual business scenarios, users may need to quickly restore the default data ordering.

implementation scheme

The methods provided by our lovely colleagues have a better way to implement them. Welcome to leave a message:

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();
        };
    }
}

effect demonstration

This account continues to share Avalonia's practical skills. Welcome attention, maintain communication, and make progress together.

Keep Exploring

延伸阅读

更多文章