Xamarin Forms:具有可绑定属性的 IMarkupExtension 不起作用 [英] Xamarin Forms: IMarkupExtension with bindable property does not work

查看:16
本文介绍了Xamarin Forms:具有可绑定属性的 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}}" />

图像资源扩展

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

这篇关于Xamarin Forms:具有可绑定属性的 IMarkupExtension 不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆