【问题标题】:MarkupExtension not working with Label?MarkupExtension 不适用于标签?
【发布时间】:2017-07-15 01:36:57
【问题描述】:

我不明白为什么我的 MarkupExtension StringFormat 不能与标签一起使用,但可以完美地与 TextBlocks 一起使用。

这是我的代码的简化版本:

[MarkupExtensionReturnType(typeof (BindingExpression))]
public class Format : MarkupExtension
{
    #region Public Properties

    public BindingBase Binding { get; set; }

    public IValueConverter Converter { get; set; }

    public string StringFormat { get; set; }

    #endregion

    #region Public Methods and Operators

    public override object ProvideValue(IServiceProvider serviceProvider)
    {
        this.Binding.StringFormat = this.StringFormat;
        return this.Binding.ProvideValue(serviceProvider);
    }

    #endregion
}

还有 XAML:

<TextBlock Text="{wpfApplication31:Format Binding={Binding Name}, StringFormat=X_{0}}" /> <!-- StringFormat WORKING -->
<Label Content="{wpfApplication31:Format Binding={Binding Name}, StringFormat=X_{0}}" /> <!-- StringFormat NOT WORKING -->

属性“名称”是一个简单的字符串。

我认为这与 Label 是一个比 TextBlock 更复杂的对象有关,但我仍然不明白为什么不应用 StringFormat。

如果有人可以提供帮助。 谢谢

【问题讨论】:

  • 我知道我可以在 Binding 中实现 StringFormat,但正如我所说,它是一个简化版本,我需要 MarkupExtension 中的 StringFormat。

标签: xaml string-formatting markup-extensions


【解决方案1】:

来自this answer

这不起作用的原因是Label.Content 属性的类型为Object,而Binding.StringFormat 仅在绑定到String 类型的属性时使用。

要使其正常工作,您需要调整 MarkupExtension 的行为,使其在用于 Label.Content 属性时设置 Label.ContentStringFormat。您可以使用收到的IServiceProvider 作为ProvideValue 方法的第一个参数。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-08-17
    • 1970-01-01
    • 1970-01-01
    • 2020-05-25
    • 2019-01-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多