10

绑定不适用于 Image 标记。调试的时候发现Extension类中Source的值总是null?但标签的内容不为空。

Xaml

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

图像资源扩展

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

1 回答 1

13

当然不是!

这不是因为你神奇地继承BindableObject了你的对象有一个BindingContext集合。没有 a 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 并在您的 Bindings 中使用它

<Label Text="{Binding Image}" />
<Image Source="{Binding Image, Converter={StaticResource myConverter}}" />
于 2017-03-07T14:31:28.173 回答