avalonia小竅門之datagrid添加取消排序

avalonia小竅門之datagrid添加取消排序

默認點擊列頭只有升序、降序排序,無法取消

最后更新 2025/7/17 下午10: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

延伸阅读

更多文章