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

时间:2017-03-07 12:28:17

标签: xamarin binding xamarin.forms bindable

绑定不适用于Image标记。 当我调试时,我看到Extension类中的Source值始终为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 个答案:

答案 0 :(得分: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 ();
    }
}

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

<Label Text="{Binding Image}" />
<Image Source="{Binding Image, Converter={StaticResource myConverter}}" />