Search code examples
c#data-bindingmauimultibindingimultivalueconverter

Multibinding giving null values to IMultiValueConverter in .NET MAUI


So I have this label in a ContentPage where SelectedTime and Type are both values in my viewmodel:

<converters:DateConverter x:Key="DateConverter" />
...
<Label>
    <Label.Text>
        <MultiBinding Converter="{StaticResource DateConverter}">
            <Binding Path="SelectedTime" />
            <Binding Path="Type" />
        </MultiBinding>
    </Label.Text>
</Label>

DateConverter is an IMultiValueConverter and when I set a breakpoint in the converter, I see that object[] values contains 2 null values, instead of their actual values. I know they are not actually null because of the scenarios below.

I have narrowed down the problem to the converter because when I try this, SelectedTime is not null and works fine. (OtherDateConverter is an IValueConverter)

<Label Text="{Binding SelectedTime, Converter={StaticResource OtherDateConverter}}" />

Using this syntax also works.

<Label>
    <Label.Text>
        <Binding Path="SelectedTime" Converter="{StaticResource OtherDateConverter}" />
    </Label.Text>
</Label>

and if I remove the converter, SelectedTime appears on my page correctly and isn't null. I can also put Type first and that works too.

<Label>
    <Label.Text>
        <MultiBinding StringFormat={'{0}'}>
            <Binding Path="SelectedTime" />
            <Binding Path="Type" />
        </MultiBinding>
    </Label.Text>
</Label>

DateConverter:

class DateConverter : IMultiValueConverter
{
    public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
    {
        // removed logic for simplicity
        return values;
    }

    public object[] ConvertBack(object value, Type[] targetTypea, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

Solution

  • Figured it out thanks to @lidqy. Those values appeared null for the first few runs during initialization but then the actual values appeared as expected. So all I had to do was add a null check like the code below to skip until the real values appeared.

    if (values[0] == null || values[1] == null)
        return "";