如果您希望视图对源集合进行排序,您可以将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