views:

84

answers:

1

I am using WPF 4.0 TextBox and binding. I am using StringFormat to format the number as currency. the XAML looks like this:

<TextBox Text="{Binding Path=ValueProperty, ValidatesOnDataErrors=True, ValidatesOnExceptions=True, StringFormat={}{0:C}, UpdateSourceTrigger=PropertyChanged}">
</TextBox>

Everything seems to work correctly except for a strange behavior: When for example a user types in 12: right after typing 1, the value in the textbox becomes $1.00 and the weird thing is the the cursor is moved to be between the $ and the 1. So when a user simply types in 12, the result becomes $21.00.

How can I fix this strange behavior?

+4  A: 

I'd change your UpdateSourceTrigger back to the default (for TextBox) of LostFocus.

By setting it to PropertyChanged, you're forcing your validation, and the string format, to run every time the user types a character. This causes very odd behavior, such as what you're seeing.

If you leave it the default (or set it back to LostFocus explicitly), the formatting + validation will happen when the user finishes typing completely. This will eliminate the strange problems that happen by StringFormat inserting new characters, validation breaking part way through, and other issues you will run into using PropertyChanged.

Reed Copsey
+1 apt answer...
Veer