我有一些代码可以监听数据网格的“排序”事件,以便能够添加自定义排序器...
我在加载数据网格时添加了它。
grid.Sorting += (sender, args) =>
{
var column = (DataGridCustomTextColumn) args.Column;
//i do some custom checking based on column to get the right comparer
//i have different comparers for different columns. I also handle the sort direction
//in my comparer
// prevent the built-in sort from sorting
args.Handled = true;
var direction = (column.SortDirection != ListSortDirection.Ascending)
? ListSortDirection.Ascending
: ListSortDirection.Descending;
//set the sort order on the column
column.SortDirection = direction;
//use a ListCollectionView to do the sort.
var lcv = (ListCollectionView) CollectionViewSource.GetDefaultView(grid.ItemsSource);
//this is my custom sorter it just derives from IComparer and has a few properties
//you could just apply the comparer but i needed to do a few extra bits and pieces
var comparer = new DataGridCommonSort(column.RealDataType, column.SortMemberPath, direction);
//apply the sort
lcv.CustomSort = comparer;
};
问题在于,仅当我单击columnheader时才调用此处理程序。 但是我需要一种方法来初始化触发数据被排序的事件
有什么想法吗? 我尝试了类似的方法:
ICollectionView dataView = CollectionViewSource.GetDefaultView(dataGrid.ItemsSource);
dataView.SortDescriptions.Clear();
dataView.SortDescriptions.Add(new SortDescription(c.SortMemberPath, ListSortDirection.Descending));
dataView.Refresh();
但这对我不起作用。
答案 0 :(得分:0)
您可以将事件处理程序定义为(非匿名)方法:
private void grid_Sorting(object sender, DataGridSortingEventArgs args)
{
//same code as before...
}
...,并在设置ItemsSource
属性后直接调用它:
grid_Sorting(grid, new DataGridSortingEventArgs(grid.Columns[0])); //sort by the first column