Xamarin Forms: 具有可绑定属性的IMarkupExtension无法工作

11

Image标签绑定未能正常工作。 调试时发现Extension类中的Source值始终为null? 但标签内容不为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;
    }
}

你是在尝试加载一个嵌入式资源还是一个资产图像? - Malte Goetz
还没有尝试您的示例,但是BindableProperty声明不正确。声明类型参数应该是typeof(ImageResourceExtension),而不是typeof(string)。但是如下面的答案中所提到的,您应该使用转换器。 - Andrew Tavera
1个回答

13
当然不会!仅仅因为您从BindableObject继承并不会使您的对象自动设置一个BindingContext。而没有BindingContext,就无法解析{Binding Image}。在这里,您需要寻找的是一个转换器(Converter)。
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}}" />

假设您需要传递多个参数,其中一个是绑定值?我有一个转换器,我开始重新制作自定义标记,以添加第三个输入[未绑定],直到我发现自定义标记无法处理绑定。 - ToolmakerSteve
没事,我刚刚找到了这个:带有多个参数的转换器? - ToolmakerSteve

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接