【问题标题】:Xamarin.Forms MarkupExtension for binding用于绑定的 Xamarin.Forms MarkupExtension
【发布时间】:2017-06-18 17:08:57
【问题描述】:

我想制作附加标记以简化出价。 我有字典,我将该属性绑定到视图中的标签。 我有 ValueConverter 接受这个字典,我通过 ConverterParameter 这是一个字符串,它找到了

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

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

我想要一个标记扩展,让我可以这样写:

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

此标记应生成与名为“Tanslations”的属性的绑定,其 valueconverter 为 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);
    }
}

标签上不显示任何内容。

【问题讨论】:

  • 文本是字符串,所以标记扩展需要提供来自ProvideValue的字符串,和Binding标记扩展一样。让一个标记扩展返回另一个是行不通的。
  • Xamarin.Forms 已经有推荐的方法来执行此操作。请看developer.xamarin.com/guides/xamarin-forms/advanced/…

标签: c# xamarin data-binding xamarin.forms converter


【解决方案1】:

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

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

如果您使用正确的名称,您所做的可能适用于普通 Xaml 解析器,这与您粘贴的名称不同),但在打开 XamlC 时肯定不会。你应该像这样实现IMarkupExtension&lt;BindingBase&gt;,而不是实现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}"/>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-05-06
    • 1970-01-01
    • 2011-08-14
    • 2020-11-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多