如果您希望視圖對源集合進行排序,您可以將DataGrid
的ItemsSource
屬性轉換爲您的集合類型並對其進行排序。當然,這需要您知道如何對排序集合進行排序以及您正在處理的源集合類型。
如果_manager.Library.Songs
是List<T>
例如,你可以使用List<T>.Sort
方法對它進行排序:
private void dg_Sorting(object sender, DataGridSortingEventArgs e)
{
var sourceCollection = dg.ItemsSource as List<Item>;
if (sourceCollection != null)
{
var sortDirection = e.Column.SortDirection;
switch (sortDirection)
{
default:
case ListSortDirection.Descending:
sortDirection = ListSortDirection.Ascending;
break;
case ListSortDirection.Ascending:
sortDirection = ListSortDirection.Descending;
break;
}
int direction = (sortDirection == ListSortDirection.Ascending ? 1 : -1);
string property = e.Column.SortMemberPath;
switch (property)
{
case nameof(Item.X):
sourceCollection.Sort((x, y) => x.X.CompareTo(y.X) * direction);
break;
//...and so on for all properties/columns
}
}
}
但在一般的視圖是不應該,它被綁定到源集合進行排序。
來源
2017-05-31 09:42:06
mm8
爲什麼以及何時要對來源集合進行排序,即_manager.Library.Songs? – mm8
因爲我使用該數據源作爲「播放列表」,所以順序應該與視圖相同,並且像點擊通常情況下那樣點擊柱狀標頭。 – JC97
這個答案是爲winforms,但我不能將其轉換爲WPF(因爲我是新來的WPF):https://stackoverflow.com/a/2551416/5985593 – JC97