我想制作标记扩展以简化出价。我有字典,我将该属性绑定到视图中的标签。我有接受这个字典的价值转换器,我传递转换器参数,它是一个字符串,它找到
<Label Text="{Binding Tanslations,Converter={StaticResource TranslationWithKeyConverter}, ConverterParameter='Test'}"/>
但我必须对不同的标签做同样的事情,但键(转换器参数)会不同,其余的将保持不变
我想要一个标记扩展,允许我写这个:
<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 编译器可以在已知的标记扩展上执行一些优化技巧,但不能在您的标记扩展上执行。
现在你被警告了,我们可以继续前进了。
您所做的可能适用于普通的 Xaml 分析器,前提是您使用正确的名称,与您粘贴的名称不同),但肯定不适用于打开 XamlC。与其实现IMarkupExtension
,不如实现这样的IMarkupExtension<BindingBase>
:
[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}"/>