WPF的奇怪问题Textbox stringformat - 光标移回 [英] strange Problem with WPF Textbox stringformat - Cursor moves back

查看:574
本文介绍了WPF的奇怪问题Textbox stringformat - 光标移回的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用WPF 4.0 TextBox和绑定。我正在使用StringFormat格式化数字作为货币。 XAML看起来像这样:

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

除了一个奇怪的行为,一切似乎都正常工作:
例如,一个用户类型在12中:键入1后,文本框中的值变为$ 1.00,奇怪的是游标移动到$和1之间。
所以当用户只输入12时,结果变成$ 21.00。



如何解决这个奇怪的行为?

解决方案

我会将您的 UpdateSourceTrigger 更改回到LostFocus的默认值(对于TextBox)。



通过将其设置为PropertyChanged,您将强制验证和字符串格式,以便在每次用户键入时运行一个人物。这会导致非常奇怪的行为,例如您看到的内容。



如果将其保留为默认值(或将其重新设置为LostFocus),则格式化+验证将当用户完成打字时发生。这样可以消除StringFormat插入新字符,验证部分的错误以及使用PropertyChanged的其他问题发生的奇怪问题。


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?

解决方案

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.

这篇关于WPF的奇怪问题Textbox stringformat - 光标移回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆