Xamarin表单:具有可绑定属性的IMarkupExtension不起作用

Ali*_*ren 5 binding bindable xamarin xamarin.forms

绑定不适用于Image标记.当我调试时,我看到Extension类中的Source值始终为null?但标签的内容不是空的.

XAML

<Label Text="{Binding Image}" />
<Image Source="{classes:ImageResource Source={Binding Image}}" />
Run Code Online (Sandbox Code Playgroud)

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

Ste*_*oix 7

当然不是!

这不是因为你从BindableObject神奇地继承了你的对象BindingContext有一套.如果没有BindingContext,就没有办法解决问题了{Binding Image}.

你在这里寻找的是一个转换器

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

    public object ConvertFrom (object value, ...)
    {
        throw new NotImplementedException ();
    }
}
Run Code Online (Sandbox Code Playgroud)

然后,将此转换器添加到Xaml根元素资源(或Application.Resources,并在绑定中使用它)

<Label Text="{Binding Image}" />
<Image Source="{Binding Image, Converter={StaticResource myConverter}}" />
Run Code Online (Sandbox Code Playgroud)