これは少しトリッキーで、主に基礎となるデータソースに依存しますが、ここで私は何をすべきかです:
まず、何よりも、あなたがソート可能であるデータ型を必要としています。それは、データソースとして、私は私のデータグリッドの種類を検出し、実際のデータを訴えることができて、今
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);
}
}
:このため、私は私の基礎となるデータ型以降「SortableObservableCollection」を作成しましたがのObservableCollectionです。これを行うために、私は私の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を使用して組み合わせ(ソートホールドを行うためのインスタンスであるよりも少し良い作品あなたの列に並べ替えるときにシフトして、私は何を意味するか分かります)。