XAML Binding’s StringFormat Ignored!

Why, oh why isn’t <Label Content=”{Binding Amount, StringFormat=C}” />‘s output formatted as currency? Instead of displaying $123.90, the label shows 123.9. My StringFormat is ignored! Is WPF broken?!

Though it might seem otherwise, WPF is working just fine. The binding’s StringFormat property only applies if the binding needs to convert the bound object to a string. Since the Content property of any ContentControl (such as Label) is of type object and a string is also an object, the binding system does not need to do a conversion and so  ignores its StringFormat property.

Change the Label to a TextBlock, move the binding to its Text property and the binding’s StringFormat is applied.

<TextBlock Text=”{Binding Amount, StringFormat=C}” /> outputs $123.90.

Why? The binding subsystem knows that Text, the destination property, is of type string and so converts the non-string bound object to a string, applying StringFormat in the process.

So, how do you format the Content property of a ContentControl (such as the Label in our example)? Easy. Set the control’s ContentString property to the desired string format. If the Control’s Content property is rendered as a string—which is what happens by default with a Label control—the format specified in ContentString will be applied during the object-to-string conversion.

<Label Content=”{Binding Amount}” ContentStringFormat=”C” /> outputs $129.90!

2 thoughts on “XAML Binding’s StringFormat Ignored!

  1. Michael Lutz

    Thanks a lot! After struggeling around for almost a day and trying almost everything, I found your hint and it was exactly describing my problem.

    Michael Lutz
    BITsoft

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *