0
如何在DataGrid.ItemsSource == null時實現自定義排序?我已經使用DataGrid.Items.Add()將項增量添加到DataGrid,而不是分配ItemsSource,因此我的ItemsSource總是顯示爲空。我想使用這樣的排序處理程序(下面)但((DataGrid)發件人).ItemsSource始終爲空。該怎麼辦?如何在ItemsSource == null時對DataGrid列執行自定義排序?
public void SortHandler(object sender, DataGridSortingEventArgs e)
{
DataGridColumn column = e.Column;
if (column.DisplayIndex == 1)
{
IComparer comparer = null;
//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
e.Handled = true;
ListSortDirection 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.
ListCollectionView lcv = (ListCollectionView)CollectionViewSource.GetDefaultView(((DataGrid)sender).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
comparer = new MySort(direction, column);
//apply the sort
lcv.CustomSort = comparer;
}
else
{
e.Handled = false;
}
}