C# 绑定属性中WPF文本的快捷方式
下面的文本在my XAML文件中重复了很多次,只更改了C# 绑定属性中WPF文本的快捷方式,c#,wpf,xaml,data-binding,windows-phone-8,C#,Wpf,Xaml,Data Binding,Windows Phone 8,下面的文本在my XAML文件中重复了很多次,只更改了ConverterParameter: <TextBlock Text="{Binding TextResource, Converter={StaticResource MyConverter}, ConverterParameter=MyText }"> 是否可以为其创建快捷方式 可能是这样的: <TextBlock Text="{MyBinding Param=MyText }"> [MarkupExte
ConverterParameter
:
<TextBlock Text="{Binding TextResource, Converter={StaticResource MyConverter}, ConverterParameter=MyText }">
是否可以为其创建快捷方式
可能是这样的:
<TextBlock Text="{MyBinding Param=MyText }">
[MarkupExtensionReturnType(typeof(string))]
public class MyBindingExtension : MarkupExtension
{
private readonly string _key;
public MyBindingExtension(string key)
{
_key = key;
}
public override object ProvideValue(IServiceProvider serviceProvider)
{
// TODO: your code here to retrieve the converted value.
}
}
它可以提高可读性,并有助于在转换器名称更改时进行大量更改。您可以创建自定义绑定:
public class MyBinding : Binding
{
public String Param {
get {return this.ConverterParameter.ToString();}
set {this.ConverterParameter = value;}
}
// usage: Text="{local:MyBinding Param=MyText}"
public MyBinding() : base("TextResource")
{
this.Converter = new MyConverter();
}
// usage: Text="{local:MyBinding MyText}"
public MyBinding(string param) : base("TextResource")
{
this.Converter = new MyConverter();
this.Param = param;
}
}
然后像这样使用它:
<TextBlock Text="{local:MyBinding MyText1}" />
<TextBlock Text="{local:MyBinding Param=MyText2}" />
您可以创建自定义标记扩展名。 关于CodeProject上的MarkupExtension有一个很好的教程: 您的扩展将类似于:
<TextBlock Text="{MyBinding Param=MyText }">
[MarkupExtensionReturnType(typeof(string))]
public class MyBindingExtension : MarkupExtension
{
private readonly string _key;
public MyBindingExtension(string key)
{
_key = key;
}
public override object ProvideValue(IServiceProvider serviceProvider)
{
// TODO: your code here to retrieve the converted value.
}
}
看看
MarkupExtensions
,您应该能够创建与所需类似的东西。