Search code examples
c#.netxamlmaui

Why does Converter receive Microsoft.Maui.Controls.Binding instead of value?


Fairly simple, I have two bindable properties of type string and I am trying to get true or false upon comparison check using a Converter.

(This is in AppShell, "thisShell" is the name of the root AppShell instance, Route is the property of a ShellSection https://learn.microsoft.com/en-us/dotnet/api/microsoft.maui.controls.shellsection?view=net-maui-8.0)

Consider the following code:

                     <Label>
                         <Label.Text>
                             <MultiBinding Converter="{converters:StringCompareConverter}">
                                 <Binding Source="{Binding Route}" />
                                 <Binding Source="{Binding Source={x:Reference thisShell}}" />
                             </MultiBinding>
                         </Label.Text>
                     </Label>

What I am doing wrong so that the Converter receives a Binding instance instead of the value I provided ?

Converter code:

public class StringCompareConverter : IMultiValueConverter
{
    public object Convert(object?[] value, Type targetType, object? parameter, CultureInfo culture)
    {
       
        if (value[1] != null)
        {

        }

        return false;
    }

    public object[] ConvertBack(object value, Type[] targetTypes, object? parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

Solution

  • When I was starting, two things helped me:

    First, writing bindings one by one, testing if they work, and then combining them in complex multi-bindings etc. It was way easier than trying to fix all problems at once.

    Second, there is this trick to debug them: https://learn.microsoft.com/en-us/dotnet/maui/fundamentals/data-binding/binding-path?view=net-maui-8.0#debug-complex-paths

    So in your case, to fix your problem:

    1. Remove the multi binding.
    2. Bind defining only Source, converting the output to string format {0}.
    3. If it is the correct Type, set Path to the value in that type.
    4. If its not the correct Type, change Source, go to step 2.

    Works like a charm.