Xamarin.Forms MarkupExtension for binding

别来无恙 提交于 2019-12-05 19:12:20

Let's start with the obvious warning: you shouldn't write your own MarkupExtensions only because it simplifies the syntax. The XF Xaml parser, and the XamlC Compiler can do some optimization tricks on known MarkupExtensions, but can't on yours.

Now that you're warned, we can move on.

What you do probably works for the normal Xaml parser provided you use the correct names, unlike what you pasted) but certainly does not with XamlC turned on. Instead of implementing IMarkupExtension, you should implement IMarkupExtension<BindingBase> like this:

[ContentProperty("Key")]
public sealed class WordByKeyExtension : IMarkupExtension<BindingBase>
{
    public string Key { get; set; }
    static IValueConverter converter = new TranslationWithKeyConverter();

    BindingBase IMarkupExtension<BindingBase>.ProvideValue(IServiceProvider serviceProvider)
    {
        return new Binding("Tanslations", BindingMode.OneWay, converter: converter, converterParameter: Key);
    }

    object IMarkupExtension.ProvideValue(IServiceProvider serviceProvider)
    {
        return (this as IMarkupExtension<BindingBase>).ProvideValue(serviceProvider);
    }
}

and then you can use it like in:

<Label Text="{local:WordByKey Key=Test}"/>

or

<Label Text="{local:WordByKey Test}"/>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!