Xamarin形式:具有可绑定属性的IMarkupExtension不起作用

Xamarin形式:具有可绑定属性的IMarkupExtension不起作用

问题描述:

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

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.

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

当然不是!

这不是因为您从BindableObject继承而神奇地为对象设置了BindingContext.没有BindingContext,就无法解析{Binding Image}.

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

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

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