【问题标题】:Sort DataGridColumn with null values always at bottom始终在底部使用空值对 DataGridColumn 进行排序
【发布时间】:2015-01-08 15:17:25
【问题描述】:

我希望 DataGrid 中的一列始终以空值排序。 我试图通过关注this (part 1)this (part 2) 来做到这一点。但是我的自定义排序不像我想要的那样工作。

这就是我的专栏比较方法:

private int NullableDateTimeCompare(DateTime? date1, DateTime? date2, int direction)
{
    if (date1.HasValue && date2.HasValue)
        return DateTime.Compare(date1.Value, date2.Value)*direction;
    if (!date1.HasValue && !date2.HasValue)
        return 0;
    if (date1.HasValue)
        return 1 * -direction; // Tried different things but nothing work like I will
    return -1 * -direction; // Tried different things but nothing work like I will
}

我的印象是这不起作用,因为 DataGrid 缓存了比较结果,因此在用户排序时会反转排序(并且不要再次运行比较)。

你知道怎么做吗?

谢谢!

【问题讨论】:

  • 如果您总是希望底部有空值,那么空值和非空值之间的比较不应受方向影响。

标签: c# wpf sorting datagrid compare


【解决方案1】:

按照您当前的代码,以下将返回 1

NullableDateTimeCompare(DateTime.Now, null, -1);
NullableDateTimeCompare(null, DateTime.Now, 1);

这些将返回 -1

NullableDateTimeCompare(DateTime.Now, null, 1);
NullableDateTimeCompare(null, DateTime.Now, -1);

但你想要的是让这些返回 1

NullableDateTimeCompare(DateTime.Now, null, -1);
NullableDateTimeCompare(DateTime.Now, null, 1);

这些返回 -1

NullableDateTimeCompare(null, DateTime.Now, 1);
NullableDateTimeCompare(null, DateTime.Now, -1);

要实现这一点,只需在函数末尾返回 1 或 -1

if (date1.HasValue)
    return 1;
return -1;

【讨论】:

  • 我一开始试过这个,但没用。所以我认为,当上升空必须得到高分,下降必须有低分。但它也没有工作......
  • 如果你希望它们在最后而不考虑升序或降序,空值应该得到一个低值或 -1,这是我假设你想要的。
  • 好的,但它不起作用。自己试试看。您可以从我在描述中提供的链接下载示例项目。
【解决方案2】:

我正在制作一个简单的项目来与您分享以解释我的问题。我找到了解决方案。

这就像@juharr 的回答,但反过来。

if (date1.HasValue)
    return -1;
return 1;

不知道为什么一定是这样,但它确实有效。空值始终位于底部。

感谢@juharr!

【讨论】:

  • date1IComparer.Compare 方法的第一个参数,date2 是第二个参数。如果你交换它们,那么这就解释了为什么你必须做相反的事情。
  • 我没有交换它们。这就是为什么我觉得这很奇怪。
猜你喜欢
  • 1970-01-01
  • 2011-12-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-11-04
  • 1970-01-01
  • 1970-01-01
  • 2011-06-22
相关资源
最近更新 更多