c# - WPF Datagrid 对具有空元素的列进行排序

标签 c# .net wpf sorting datagrid

我有一个 WPF 数据网格,我正在使用它和许多列。其中一列包含一些有时为空的元素,当我尝试对此列进行排序时,这会导致异常。

列的定义是这样的:

<dg:DataGrid.Columns>
  <dg:DataGridTextColumn Binding="{Binding MyObject.Field1}" Header="Field1" Width="Auto" />
  <dg:DataGridTextColumn Binding="{Binding MyObject.Field2.SubField}" Header="Field2" Width="Auto" />
</dg:DataGrid.Columns>

如果我在 Field1 列上排序没问题,如果我在 Field2 列上排序并且没有空的 Field2 对象,那没问题,但有时有并且 DataGrid 尝试在 SubField 上排序(我猜)并点击空异常:

System.InvalidOperationException was unhandled
  Message=The SortDescriptions added are not valid. The probable solutions are to set the CanUserSort on the Column to false, or to use SortMemberPath property on the Column, or to handle the Sorting event on DataGrid.

我已尝试将 SortMemberPath 设置为“MyObject.Field2.SubField”,但当然这不能解决问题,因为 Field2 有时仍为空。我想知道是否尝试在我设置 SortMemberPath 的地方使用转换器,并让该转换器为任何 null 元素返回 string.empty 但无法使其工作。

我还尝试在这些列的绑定(bind)中添加“TargetNullValue={x:Static sys:String.Empty}”,但它仍然不起作用。

如有任何意见/建议,我们将不胜感激。 谢谢, 将

最佳答案

一般建议是:不要使用 SortMemberPath。不仅仅是因为你刚刚遇到的问题。但也因为它们超慢。

改为使用 ListCollectionView 类的 CustomSort 属性。有关详细信息,请阅读 "Improving Microsoft DataGrid CTP sorting performance""Improving Microsoft DataGrid CTP sorting performance - Part 2" .虽然它说“提高性能”,但它也显示了如何解决您的问题。

希望这有帮助:)。

关于c# - WPF Datagrid 对具有空元素的列进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1645823/

相关文章:

c# - 使用 C# Windows 10 是否可以判断视频/相机当前是否被任何应用程序使用?

c# - 使用 WinForms 在 C# 中为 TableLayoutPanel 创建动态 Controller 名称

C# 在文件中搜索字符串并获取字符串的行号

.net - Parallel.Foreach 产生太多线程

c# - 保存 .NET 用户设置需要很长时间

c# - 为什么要使用 IList 或 List?

c# - C# 项目的目标是 ".NetFramework, Version=v4.5,Profile=Unity Full v3.5",它没有安装在这台机器上

c# - 如何在 C# 中按名称查找动态创建的 XAML 组件?

c# - 从线程启动时模态弹出窗口失败 - CSharp WPF

wpf - 如何获取 UIElement 的父级?