我有一个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列排序,并且没有任何null的Field2对象,则也很好。但有时候存在null的Field2对象,DataGrid尝试对SubField进行排序(我猜是这样),然后就会出现null异常。
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,但无法使其正常工作。
我还尝试在这些列的绑定中添加"TargetNullValue={x:Static sys:String.Empty}",但仍然无法解决问题。
如有建议/建议,将不胜感激。 谢谢, 威尔