Avalonia小窍门之DataGrid添加取消排序

Avalonia小窍门之DataGrid添加取消排序

默认点击列头只有升序、降序排序,无法取消

最后更新 2025-07-17 22:57
沙漠尽头的狼
预计阅读 1 分钟
分类
Avalonia UI
标签
.NET C# Avalonia UI 交互设计 Avalonia

需求背景

默认DataGrid点击列头只能在升序(↑)、降序(↓)两种状态间切换:

但在实际业务场景中,用户可能需要快速恢复默认数据排序。

实现方案

可爱的同事提供的方法,有更好的实现方式欢迎留言:

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

效果演示

本号持续分享Avalonia实战技巧,欢迎关注,保持交流,共同进步。

Keep Exploring

延伸阅读

更多文章