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.
The definitions of the columns is something like:
<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>
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.
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.
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
General advice would be: Don't use SortMemberPath. Not only because of the problem you've just met. But also because they are ultraslow.
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.
Hope this helps :).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With