這是一個有點棘手,在很大程度上依賴的基礎數據源,但這裏是我做的:
首先,也是最重要的,你需要的是一個可排序的數據類型。對於這一點,我創建了一個「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的物品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在做着合併排序的實例(持有好一點在對列進行排序時向下移動,你會看到我的意思)。