需求背景
默認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實戰技巧,歡迎關注,保持交流,共同進步。