当DataGrid.ItemsSource == null时,如何实现自定义排序?我已经使用DataGrid.Items.Add()以递增方式将项添加到DataGrid而不是分配ItemsSource,因此我的ItemsSource似乎总是为null。我想使用像这样的排序处理程序(下面)但((DataGrid)发送者).ItemsSource始终为null。怎么办?
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;
}
}
答案 0 :(得分:0)
WPF的强大功能是绑定支持,所以为什么不使用它。因此,我建议您将dataGrid的ItemSource绑定到类中的ObservableCollection
,并将项添加到此集合中。
使用ObservableCollection
实现的INotifyCollectionChanged
带来的好处,这样您就不必担心UI刷新问题了。添加项目后,项目将在您的UI上更新。
此外,您可以使用CollectionViewSource
。请参阅此文章 - http://bea.stollnitz.com/blog/?p=387