1

I don't understand why my MarkupExtension StringFormat does not work with labels but works perfectly with TextBlocks.

Here is a simplified version of my code:

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

And the 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 -->

The property 'Name' is a simple string.

I think it's related to the fact that Label is a more complex object than TextBlock but I still don't understand why the StringFormat is not applied.

If anybody can help. Thx

PlaTyPuS
  • 385
  • 3
  • 15
  • I know I can achieve the StringFormat in the Binding but as I said, it's a simplified version and I need the StringFormat in the MarkupExtension. – PlaTyPuS Feb 24 '17 at 09:24

1 Answers1

0

From this answer :

The reason this doesn't work is that the Label.Content property is of type Object, and Binding.StringFormat is only used when binding to a property of type String.

And to make it work you'd need to adapt the behaviour of your MarkupExtension to make it set the Label.ContentStringFormat when it's used for the Label.Content property. You can use the IServiceProvider that you recieve as the first parameter of the ProvideValue method.

nalka
  • 1,894
  • 11
  • 26