Xamarin.Forms 用于绑定的 MarkupExtension

Xamarin.Forms MarkupExtension for binding

我想制作标记扩展以简化出价。 我有字典,我将 属性 绑定到视图中的标签。 我有一个接受这个字典的 ValueConverter,我传递了一个字符串 ConverterParameter,它找到

<Label Text="{Binding Tanslations,Converter={StaticResource TranslationWithKeyConverter}, ConverterParameter='Test'}"/>

但我必须对不同的标签做同样的事情,但关键 (ConverterParameter) 会有所不同,其余的将保持不变

我想要一个允许我这样写的标记扩展:

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

此标记应生成到名为 "Tanslations" 的 属性 的绑定,其值转换器为 TranslationWithKeyConverter,ConverterParameter 的值为 Key。

我试过了但是没用:

public class WordByKey : IMarkupExtension
{
    public string Key { get; set; }
    public object ProvideValue(IServiceProvider serviceProvider)
    {
        return new Binding("Tanslations", BindingMode.OneWay, converter: new TranslationWithKeyConverter(), converterParameter: Key);
    }
}

标签上没有显示任何内容。

让我们从明显的警告开始:您不应该仅仅因为它简化了语法而编写自己的 MarkupExtensions。 XF Xaml 解析器和 XamlC 编译器可以对已知的 MarkupExtensions 做一些优化技巧,但不能对你的。

现在您已收到警告,我们可以继续了。

如果您使用正确的名称,您所做的可能适用于普通的 Xaml 解析器,这与您粘贴的名称不同)但肯定不适用于 XamlC 打开。你应该像这样实现 IMarkupExtension<BindingBase>,而不是实现 IMarkupExtension

[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);
    }
}

然后你可以像这样使用它:

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

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