Xamarin Forms: IMarkupExtension with bindable property does not work

大兔子大兔子 提交于 2019-12-10 14:29:03

问题


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;
    }
}

回答1:


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}}" />


来源:https://stackoverflow.com/questions/42648334/xamarin-forms-imarkupextension-with-bindable-property-does-not-work

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!