How to use XAML binding with the following {Binding Model.Errors[ClassName.PropertyName]}

Viewed 445

Binding in xaml spits out the following error:

System.FormatException: Indexer did not contain closing bracket

How can I provide the class and property name as a string value inside the Model.Errors[string value with dot(s) here]

This works

Text="{Binding User.Errors[Forename]}"

This does not when trying to add the string value with a dot

<Label Text="{Binding User.Errors[UserDetail.PhoneNumber]}" />

Having the dot allows me to have the scope of the inner class and property name on the c# side. I could replace the dot with a + but then I'm assuming I would have to build some converter to change the + to a dot when it reaches the c# side?

Not sure if there is some other kind of format or way to achieve this, without writing out the additional converter logic?

1 Answers

Use the source, Luke: Xamarin's XAML parser apparently does not allow such syntax: it doesn't parse the path properly, but just splits the whole path string by .. To work around this limitation, I suggest a minimal value converter that lets you keep the . for member access:

// error handling and boilerplate omitted
public class ErrorConverter : IValueConverter
{
    public object Convert (object value, Type targetType,
        object parameter, CultureInfo culture)
    {
        return ((ErrorCollection) value)[(string)parameter] ;
    }
}

Then use it in bindings like this:

<Label Text="{Binding User.Errors, Converter={StaticResource ErrorConverter},
     ConverterParameter='UserDetail.PhoneNumber'}" />
Related