WPF--实现代码控制DataGrid的特定列排序

此方法适用于 WPF 的 DataGrid 控件。

1、后台定义方法
///
/// 模拟点击列头
///
/// 列名
/// 降序还是升序
private void DataGridSort(string ColumnName, ListSortDirection DescOrAsce)

    {

        ICollectionView v = CollectionViewSource.GetDefaultView(dataGrid1.ItemsSource);
        v.SortDescriptions.Clear();
        v.SortDescriptions.Add(new SortDescription(ColumnName, DescOrAsce));
        v.Refresh();
        this.dataGrid1.ColumnFromDisplayIndex(0).SortDirection = DescOrAsce;

    }

2、调用方法
//按钮事件或者其它事件
private void button1_Click(object sender, RoutedEventArgs e)
{
//用法
DataGridSort(“列绑定的字段名字”, ListSortDirection.Ascending);
}
3、获取排序后的结果集合
var temp=控件名.Items.Cast().Select(x => x as 类名).ToList();//界面字段排序后的集合

程序如下所示:
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_41883890/article/details/128955877