WPF Datagrid 对具有空元素的列进行排序 [英] WPF Datagrid sort on column with null elements

查看:24
本文介绍了WPF Datagrid 对具有空元素的列进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 WPF Datagrid,我将它与许多列一起使用.其中一列有一些元素有时为空,这会在我尝试对此列进行排序时导致异常.

I have a WPF Datagrid that I am using with a number of columns. One of the columns has some elements that are sometimes null and this causes an exception when I try and sort on this column.

列的定义类似于:

<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 上排序(我猜)并点击空异常:

If I sort on Field1 column it is fine, if I sort on Field2 column and there are no null Field2 objects it is fine, but sometimes there are and the DataGrid tries to sort on the SubField (I guess) and hits a null exception:

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 并让该转换器为任何空元素返回 string.empty 但无法让它工作.

I have tried setting SortMemberPath to "MyObject.Field2.SubField" but of course this doesn't fix it since Field2 is still sometimes null. I wondered about trying to use a converter where I set the SortMemberPath and have that converter return string.empty for any null elements but couldn't get it to work.

我也尝试在这些列的绑定中添加TargetNullValue={x:Static sys:String.Empty}",但它仍然不起作用.

I also tried adding "TargetNullValue={x:Static sys:String.Empty}" within the binding of these columns but it still did not work.

任何建议/建议将不胜感激.谢谢,将

Any advice/suggestions would be most appreciated. Thanks, Will

推荐答案

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

General advice would be: Don't use SortMemberPath. Not only because of the problem you've just met. But also because they are ultraslow.

改为使用 ListCollectionView 类的 CustomSort 属性.有关详细信息,请阅读 "提高 Microsoft DataGrid CTP 排序性能""提高 Microsoft DataGrid CTP 排序性能 - 第 2 部分".虽然它说提高性能",但它也显示了如何解决您的问题.

Instead use CustomSort property of the ListCollectionView class. For more details read "Improving Microsoft DataGrid CTP sorting performance" and "Improving Microsoft DataGrid CTP sorting performance - Part 2". Although it says "imporve performance" it also shows how to fix your problem.

希望这有帮助:)

这篇关于WPF Datagrid 对具有空元素的列进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆