Search code examples
c#.netwpfbindingiformatprovider

Any built in way to format WPF bindings?


Scenario

I can't seem to find a way to format bindings in WPF using an IFormatProvider. Currently I've a property on my data source:

public int PersonNumber { get; set; }

This property is bound to a Label in XAML:

<Label Content="{Binding Path=PersonNumber}" />

As you can see it's a number, but should be formatted like 0000.00.000. Currently we use a separate IFormatProvider for such things in our old WinForms application.

Questions

  • Is formatting like this possible in WPF?
    • If yes, our preferred way is to still use an IFormatProvider, also possible?
    • If no, what is a good alternative?

Thanks in advance!


Solution

  • You're looking for the ContentStringFormat property, which is on all ContentControl descendants including Label.

    <Label Content="{Binding PersonNumber}" ContentStringFormat="000" />
    

    I'm not sure whether WPF's formatting can make use of an IFormatProvider, though.