联系请关注微信公众号:Dotnet9
更新于2025-07-17 22:57:14| 沙漠尽头的狼| 我要编辑、留言
Avalonia小窍门之DataGrid添加取消排序

Ai摘要

摘要由站长通过智能技术生成

需求背景

默认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实战技巧,欢迎关注,保持交流,共同进步。

网站统计
网站创建
6年
文章分类
22个
文章总计
506篇
文章原创
116篇(22.92%)