我有一个包含3列的WPF DataGrid。对于前两列,我想要默认排序,但对于第三列,我想要按升序/降序排序。 我已经在datagrid上处理了排序事件,如下所示:
private void ReleaseDataGrid_Sorting(object sender, DataGridSortingEventArgs e)
{
ListSortDirection direction = (e.Column.SortDirection != ListSortDirection.Ascending) ? ListSortDirection.Ascending : ListSortDirection.Descending;
if (e.Column.SortMemberPath == "DisplayName")
{
SortStatusImg.Visibility = System.Windows.Visibility.Collapsed;
SortVersionImg.Visibility = System.Windows.Visibility.Collapsed;
SortPackageNameImg.Visibility = System.Windows.Visibility.Visible;
if (direction == ListSortDirection.Ascending)
{
SortPackageNameImg.Source = new BitmapImage(new Uri(@"pack://application:,,,/Resources/sortup.png"));
}
else
{
SortPackageNameImg.Source = new BitmapImage(new Uri(@"pack://application:,,,/Resources/sortdown.png"));
}
}
else if (e.Column.SortMemberPath == "UserMachineStatus")
{
SortStatusImg.Visibility = System.Windows.Visibility.Visible;
SortVersionImg.Visibility = System.Windows.Visibility.Collapsed;
SortPackageNameImg.Visibility = System.Windows.Visibility.Collapsed;
if (direction == ListSortDirection.Ascending)
{
SortStatusImg.Source = new BitmapImage(new Uri(@"pack://application:,,,/Resources/sortup.png"));
}
else
{
SortStatusImg.Source = new BitmapImage(new Uri(@"pack://application:,,,/Resources/sortdown.png"));
}
}
else if (e.Column.SortMemberPath == "ReleaseInfo")
{
DisplayReleaseList.Sort(new VersionComparerDesc());
SortStatusImg.Visibility = System.Windows.Visibility.Collapsed;
SortVersionImg.Visibility = System.Windows.Visibility.Visible;
SortPackageNameImg.Visibility = System.Windows.Visibility.Collapsed;
if (direction == ListSortDirection.Ascending)
{
SortVersionImg.Source = new BitmapImage(new Uri(@"pack://application:,,,/Resources/sortup.png"));
DisplayReleaseList.Sort(new VersionComparer());
}
else
{
SortVersionImg.Source = new BitmapImage(new Uri(@"pack://application:,,,/Resources/sortdown.png"));
DisplayReleaseList.Sort(new VersionComparerDesc());
}
RefreshMediaGrid();
e.Handled = true;
}
}
对于前两列,它工作正常。但是对于自定义排序列,它按升序排序一次,后来无论我点击列标题多少次都没有排序。
当我按第三列排序时,ListSortDirection始终为null,因此当控件进入此方法时,始终为方向分配ListSortDirection.Ascending
它不保留排序方向。请帮忙。
答案 0 :(得分:0)
您应该设置列的SortDirection
属性:
private void ReleaseDataGrid_Sorting(object sender, DataGridSortingEventArgs e)
{
if (e.Column.SortMemberPath == "ReleaseInfo")
{
e.Handled = true;
ListSortDirection direction = (e.Column.SortDirection != ListSortDirection.Ascending) ? ListSortDirection.Ascending : ListSortDirection.Descending;
e.Column.SortDirection = direction;
//sort according to your logic...
}
}
这会使箭头在列标题中按预期显示。