如何在 WPF 文本框中的百分比格式字段上进行简单编辑?
当您将文本框格式化为货币并单击编辑它时,$和逗号不会引起问题,您可以直接编辑和制表符,没有问题。当您将字段格式化为百分比时,事情就不太顺利了。
<TextBox Text="{Binding CostMarkup,
StringFormat=P}"
Style="{StaticResource ctrlSpacingTight}" />
如果基础值是 0.1,它会正确显示为 10%,如果您去编辑,它仍然显示为 10%,% 将导致问题,而且它将把基础值从 0.1 更改为 10。我编写了一个转换器来处理所有但我想知道是否有更好的方法。特别是有没有办法像货币处理它一样处理它?
有一个内置的货币转换器,所以我怀疑 StringFormat 的货币版本使用它。虽然有 ZoomPerentageConverter,但它并没有达到我的预期。有没有办法挂钩 StringFormat=P 并让它调用我的转换器,而不必转到每个实例并显式指定它?
<TextBox Text="{Binding CostMarkup,
StringFormat=P,
Converter={StaticResource pctConverter}}"
Style="{StaticResource ctrlSpacingTight}" />
When you format a TextBox as currency and click to edit it, the $ and commas do not cause a problem, you can just edit and tab with no problem. When you format a field as a percentage things do not work so well.
<TextBox Text="{Binding CostMarkup,
StringFormat=P}"
Style="{StaticResource ctrlSpacingTight}" />
If the underlying value is 0.1 it correctly displays as 10%, if you go to edit it still shows as 10% the % will cause a problem plus it will change the underlying value from .1 to 10. I wrote a Converter to handle all this but I'm wondering if there isn't a better way. In particular is there a way to handle it the way currency handles it?
There is a built in currency converter so I suspect the currency version of StringFormat uses that. While there is a ZoomPerentageConverter it doesn't do what I would expect. Is there a way to hook in to StringFormat=P and have it invoke my Converter instead of having to go to every instance and explicitly specify it?
<TextBox Text="{Binding CostMarkup,
StringFormat=P,
Converter={StaticResource pctConverter}}"
Style="{StaticResource ctrlSpacingTight}" />
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我总是发现在编辑时显示原始数据是最简单的,而在不编辑时显示格式化值是最简单的。
下面是使用触发器执行此操作的示例。
如果
ctrlSpacingTight
是全局样式,您可以为 TextBox 创建一个BasedOn
全局样式的样式。I've always found that it's easiest to display the raw data when editing, and the formatted value when not.
Here's an example that does that using a trigger
If
ctrlSpacingTight
is a global style, you can create a style for your TextBox that isBasedOn
your global style.