这有点棘手,很大程度上取决于底层数据源,但这是我要做的:
首先,您需要一种可排序的数据类型。为此,我创建了一个“SortableObservableCollection”,因为我的基础数据类型是 ObservableCollection:
public class SortableObservableCollection<T> : ObservableCollection<T>
{
public event EventHandler Sorted;
public void ApplySort(IEnumerable<T> sortedItems)
{
var sortedItemsList = sortedItems.ToList();
foreach (var item in sortedItemsList)
Move(IndexOf(item), sortedItemsList.IndexOf(item));
if (Sorted != null)
Sorted(this, EventArgs.Empty);
}
}
现在,使用它作为数据源,我可以在我的 DataGrid 上检测排序并使用实际数据。为此,我在 DataGrid 的 Items 的 CollectionChanged 事件中添加了以下事件处理程序:
... In the constructor or initialization somewhere
ItemCollection view = myDataGrid.Items as ItemCollection;
((INotifyCollectionChanged)view.SortDescriptions).CollectionChanged += MyDataGrid_ItemsCollectionChanged;
...
private void MyDataGrid_ItemsCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
// This is how we detect if a sorting event has happend on the grid.
if (e.NewItems != null &&
e.NewItems.Count == 1 &&
(e.NewItems[0] is SortDescription))
{
MyItem[] myItems = new MyItem[MyDataGrid.Items.Count]; // MyItem would by type T of whatever is in the SortableObservableCollection
myDataGrid.Items.CopyTo(myItems, 0);
myDataSource.ApplySort(myItems); // MyDataSource would be the instance of SortableObservableCollection
}
}
这比使用 SortDirection 效果好一点的原因之一是在进行组合排序的情况下(对列进行排序时按住 shift 键,您会明白我的意思)。