WPF的DataGrid null元素排序的列元素、WPF、DataGrid、null

2023-09-04 00:25:30 作者:看不顺我就滚

我有一个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>

如果我排序的字段1列它是好的,如果我排序的场2列,有没有空场2对象,它是好的,但有时也有和数据网格试图在子字段进行排序(我猜),并击中空异常:

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任何null元素,但不能让它的工作。

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:静态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.

任何意见/建议将是最AP preciated。 谢谢, 请问

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财产。欲了解更多详情请继续阅读"Improving微软的DataGrid CTP排序性能和"Improving微软的DataGrid CTP排序性能 - 第2部分。虽然它说:imporve性能这也说明了如何解决您的问题。

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.

希望这有助于:)