【问题标题】:Shortcut for WPF text in Binding attributes绑定属性中 WPF 文本的快捷方式
【发布时间】:2013-11-28 03:32:03
【问题描述】:

以下文本在我的 XAML 文件中重复多次,仅更改了 ConverterParameter

<TextBlock Text="{Binding TextResource, Converter={StaticResource MyConverter}, ConverterParameter=MyText }">

是否可以为其创建快捷方式?

可能是这样的:

<TextBlock Text="{MyBinding Param=MyText }">

它可以提高可读性,并有助于在转换器名称更改的情况下进行大规模更改。

【问题讨论】:

标签: c# wpf xaml data-binding windows-phone-8


【解决方案1】:

您可以创建自定义绑定:

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}" />

【讨论】:

    【解决方案2】:

    您可以创建自定义的 MarkupExtension。 CodeProject 上有一个关于 MarkupExtension 的优秀教程: http://www.codeproject.com/Articles/140618/WPF-Tutorial-TypeConverter-Markup-Extension

    您的扩展程序如下所示:

    [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.
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-07-27
      • 1970-01-01
      • 2012-05-12
      • 2011-08-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-05
      相关资源
      最近更新 更多