WPF Binding double to TextBox Text Property

March 12, 2015

Binding to double property of some object with UpdateSourceTrigger set to PropertyChanged allows dynamically update ViewModel while user enters the number. Application become more responsive and user friendly.

Unfortuntely simple binding has frustrating editing behaviors – portion of the text are automatically erased in some cases (usually decimal separator and leading or trailing zeroes) – “cleaning up of the input”.

As an example I made a small application, converting millimeters to inches. This is how the problem looks like (please note I have German keyboard layout, decimal separator is comma):

The reason of this is quite simple as soon as string is converted into a double value and it is assigned to ViewModel dependency property, ViewModel notifies performed update, and double value transformed back to string without “unneded” separators and zeroes. This is very annoying while entering text, so decided to fix it.

The solution is quite simple – own converter which saves user input string and returns it instead of rebuilding it every time. Something like this:

Unfortunately this will not work in all cases – in example, if bound value of ViewModel will be changed from some other place of the application (in my example – changed from the other TextBox), converter will continue delivering old string value. So when TextBox looses its focus, it makes sense to set user_string to null. Also on lost focus we can format output string – clean it up (actually the same behavior which we had at the beginning, but only on Lost Focus). To do so, an attached property is introduced:

Here is the complete source code of the project: StringConversionTest. Note that ProxyConverter is extended with Scale Dependency property to implement conversion of input value from inches to millimeters.