Can I use IFormatProvider with a WPF Binding to a custom type?

2.1k Views Asked by At

I have a custom type (SINumber, which represents an SI number with appropriate units and prefix). I can bind to a SINumber fine and override SINumber.ToString(), but what is displayed is the result of calling SINumber.ToString().

For example, SIMeasurement is of type SINumber with an SI value of 3099999.9046325684 Ω. Using the following Binding, I get an output of 3.09999990463257 MΩ.

<TextBlock Text="{Binding SINMeasurement}"></TextBlock>

The units (Ω) and prefix (M = mega) conversation are correct, the problem is with the number of numerals displayed. I want to be able to use a custom formatter (implementing IFormatProvider ICustomFormatter?) to interpret the StringFormat from the Binding, and incorporate my SI-logic (changing prefix) to display 3.10 MΩ. Below is an example of the Binding I would like to use, where the precision is customizable (0.00 in this case), and the location of the units are determined by the 'U'.

<TextBlock Text="{Binding SINMeasurement, StringFormat='{}{0:0.00 U}'}"></TextBlock>

Any thoughts? I don't want to use the hard-coded SINumber.ToString(), as the desired precision will vary in different locations within the application.

Thanks in advance.

1

There are 1 best solutions below

0
On

Make your data type implements IFormattable interface. Its method public string ToString(string format, IFormatProvider formatProvider) will be called each time the Binding converts your object to string using StringFormat that you specify for the Binding.