Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

strange Problem with WPF Textbox stringformat - Cursor moves back

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?

like image 498
Emad Gabriel Avatar asked Oct 19 '25 00:10

Emad Gabriel


2 Answers

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.

like image 189
Reed Copsey Avatar answered Oct 21 '25 21:10

Reed Copsey


you can use this string format it'll fix this issue

"$###\,##0.0##"

your code should looks like

<TextBox Text="{Binding Path=ValueProperty, ValidatesOnDataErrors=True, ValidatesOnExceptions=True, StringFormat=$###\,##0.0##, UpdateSourceTrigger=PropertyChanged}">
</TextBox>
like image 23
Ahmed Ahmed Avatar answered Oct 21 '25 20:10

Ahmed Ahmed



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!