[英]Xamarin.Forms MarkupExtension for binding
我想制作扩展标记以简化出价。 我有字典,我将该属性绑定到视图中的Label。 我有ValueConverter接受这个dictinary并且我传递了ConverterParameter,这是一个字符串,它找到了
<Label Text="{Binding Tanslations,Converter={StaticResource TranslationWithKeyConverter}, ConverterParameter='Test'}"/>
但我必须为不同的标签做同样的事情,但关键(ConverterParameter)将是不同的,其余将保持不变
我想要一个markupextension,这将允许我写这个:
<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);
}
}
标签上没有显示任何内容。
让我们从明显的警告开始:您不应该只编写自己的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}"/>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.