views:

389

answers:

1

Does anyone know why I'm getting a NullReference Expception at following line:

var field = (string)((Binding)((GridViewColumnHeader)e.OriginalSource).Column.DisplayMemberBinding).Path.Path;

when using this example: http://www.switchonthecode.com/comment/reply/263/2980 (based on: http://www.switchonthecode.com/tutorials/wpf-tutorial-using-the-listview-part-2-sorting)

Thanks a lot!

Cheers, Joseph

PS: This only happens when I'm sorting double/decimals, not for strings?

EDIT:

I found the problem. This is how my XAML looks like:

            <GridViewColumn Header="Double">
                <GridViewColumn.CellTemplate>
                    <DataTemplate>
                        <TextBlock Text="{Binding TotalValues, Mode=OneWay, StringFormat=\{0:0\'0.00\}, Converter={StaticResource GridValueConverter}}" TextAlignment="Right" Width="auto"/>
                    </DataTemplate>
                </GridViewColumn.CellTemplate>
            </GridViewColumn>
            <GridViewColumn Header="Comments" DisplayMemberBinding="{Binding Path=Comments, Mode=OneWay}" Width="auto"/>

The problem here is that I'm trying to get the DisplayMemberBinding, but for the double's I'm using a DataTemplate.. does anyone know how I can change the line to make it work for every Column-Type?

A: 

At a glance, it looks like the line should only be working for strings since youre casting it to a string before assigning. You might do this instead:

object field = ((Binding)((GridViewColumnHeader)e.OriginalSource).Column.DisplayMemberBinding).Path.Path;

Which won't throw any null reference exception (which is being caused by the (string) cast when the value isn't a string). If you would cast using as, you wouldn't get the exception upon cast but that won't work for value types (and would still only work for string), ie:

var field = (((Binding)((GridViewColumnHeader)e.OriginalSource).Column.DisplayMemberBinding).Path.Path as string);

so with field as an object, you can use field.GetType() to compare against typeof(string), typeof(double),... to figure out what type it is and do whatever else you need to with it.

Mark Synowiec