Search code examples
xamlxamarinbindingconverters

Xamarin form: IValueConverter receive null value in Convert method


I have a list view set with item source as child. I want to bind a child object to a view which will set the color through the converter.

The converter method got called but the value i passed in was null.

Apart from dot, I also use Path=/ but the value passed to the converter still null. If i bind the property, it's fine but not the current item.

<ListView x:Name="childListView" 
    VerticalOptions="FillAndExpand" 
    HasUnevenRows="true" 
    ItemSelected="OnItemSelected"
    ItemTapped="OnItemTapped">
    <ListView.ItemTemplate>
        <DataTemplate>
            <ViewCell>
                <ViewCell.View>
                    <StackLayout 
                        BackgroundColor="{Binding ., Converter={StaticResource accountedToColorConverter}}" 
                        Spacing="0" Padding="0" VerticalOptions="FillAndExpand" HorizontalOptions="FillAndExpand">
                        <StackLayout Orientation="Horizontal" Spacing="10" Padding="0" HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand">
                            <StackLayout Orientation="Horizontal" HorizontalOptions="StartAndExpand">
                                <controls:CircleImage>

Solution

  • Phatye is definitely correct in saying the line

    BackgroundColor="{Binding ., Converter={StaticResource accountedToColorConverter}}"

    is the culprit. I too have attempted to use the {Binding .} and {Binding Path=.} with a converter in the past only to run into the same null reference issues you're running into. It seems that Xamarin doesn't like this.

    The proper solution will be to pass the proper path of the property you want to bind to:

    Assuming the property is a top level property

    BackgroundColor="{Binding Path=accounted, Converter={StaticResource accountedToColorConverter}}"

    Otherwise you could do this:

    BackgroundColor="{Binding Path=topLevelProperty.accounted, Converter={StaticResource accountedToColorConverter}}"