ContentControl

[WPF] Formatting Content Controls

Over the past few years I haven’t done much UI work and what little I did was either with a proprietary Web framework or Windows Forms so I’m more than a little behind the curve with WPF. My most recent project has me learning WPF on the fly and although it’s a daunting task and I still have plenty to learn I’m finding it pretty straightforward. Every once in a while though something works completely different than I expect and throws me for a bit of a curve.

One such example just happened yesterday. I was trying to bind and format a value to a Button‘s Content property. I was trying to bind using the same syntax as binding to the Text property on a TextBox:

<Button Content="{Binding Percentage, StringFormat={}{0:P0}}" />

I was surprised though when the value bound properly but wasn’t formatted. After some investigation I learned that controls like Button that inherit from ContentControl can’t be formatted that way. Instead we need to use the ContentStringFormat to achieve the same effect:

<Button Content="{Binding Percentage}" ContentStringFormat="P0" />

With that change the value started showing up as the percentage just like I expected. Lesson learned.

Advertisements