11

The binding is not working for the Image tag. When I debug, I see that the value of the Source in Extension class is always null? But the content of the label is not null.

Xaml

<Label Text="{Binding Image}" />
<Image Source="{classes:ImageResource Source={Binding Image}}" />

ImageResourceExtension

// You exclude the 'Extension' suffix when using in Xaml markup
[Preserve(AllMembers = true)]
[ContentProperty("Source")]
public class ImageResourceExtension : BindableObject, IMarkupExtension
{
    public static readonly BindableProperty SourceProperty = BindableProperty.Create(nameof(Source), typeof(string), typeof(string), null);
    public string Source
    {
        get { return (string)GetValue(SourceProperty); }
        set { SetValue(SourceProperty, value); }
    }

    public object ProvideValue(IServiceProvider serviceProvider)
    {
        if (Source == null)
            return null;

        // Do your translation lookup here, using whatever method you require
        var imageSource = ImageSource.FromResource(Source);

        return imageSource;
    }
}
2
  • Are you trying to load an image which is an embedded resource or is it an asset?
    – Malte G
    Commented Mar 7, 2017 at 12:38
  • Haven't tried your example, but the BindableProperty is declared incorrectly. The declaring type parameter should be typeof(ImageResourceExtension) rather than typeof(string). But also as mentioned in the answer below, you should use a converter instead. Commented Mar 7, 2017 at 16:35

1 Answer 1

13

Of course it does not !

It's not because you inherit from BindableObject that magically your object has a BindingContext set. And without a BindingContext, there's no way to resolve the {Binding Image}.

What you're looking for here is a Converter

class ImageSourceConverter : IValueConverter
{
    public object ConvertTo (object value, ...)
    {
        return ImageSource.FromResource(Source);
    }

    public object ConvertFrom (object value, ...)
    {
        throw new NotImplementedException ();
    }
}

You then add this converter to your Xaml root element resources (or Application.Resources and use it in your Bindings

<Label Text="{Binding Image}" />
<Image Source="{Binding Image, Converter={StaticResource myConverter}}" />
2
  • Suppose you need to pass more than one parameter, one of which is a bound value? I have a converter that I started to rework into custom markup, to add a third input [which is not bound], until I discovered the custom markup couldn't handle the binding. Commented Jun 21, 2018 at 1:49
  • nm, I just found this: Converter with multipler parameters?. Commented Jun 21, 2018 at 1:52

Not the answer you're looking for? Browse other questions tagged or ask your own question.