我有一个 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 对象,那就没问题,但有时有,并且 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 并让该转换器为任何 null 元素返回 string.empty 但无法使其工作。
我还尝试在这些列的绑定中添加“TargetNullValue={x:Static sys:String.Empty}”,但它仍然不起作用。
任何意见/建议将不胜感激。
谢谢,
将要
一般建议是:不要使用 SortMemberPath。不仅仅是因为您刚刚遇到的问题。但也因为它们超慢。
而是使用 ListCollectionView 类的 CustomSort 属性。欲了解更多详细信息,请阅读“提高 Microsoft DataGrid CTP 排序性能” and “提高 Microsoft DataGrid CTP 排序性能 - 第 2 部分”。虽然它说“提高性能”,但它也展示了如何解决您的问题。
希望这可以帮助 :)。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)