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开发者_JS百科 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?
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.
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>
This issue has been fixed in .NET 4.5. For .NET 4, I had to remove StringFormat in order to keep UpdateSourceTrigger=PropertyChanged
精彩评论