具有 CurrencyFormat 和 PropertyChanged 触发器的 TextBox 不接受正确的文本 [英] TextBox with CurrencyFormat and PropertyChanged trigger doesn't accept text right

查看:14
本文介绍了具有 CurrencyFormat 和 PropertyChanged 触发器的 TextBox 不接受正确的文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 WPF 窗口中有一个 TextBox 绑定到 double 类型的窗口的依赖属性(见下文).每当用户在 TextBox 中键入时

I have a TextBox in a WPF window bound to a dependency property of the window of type double (see below). Whenever the user types in the TextBox when

  1. TextBox 为空,或
  2. 所有文本都被选中,

输入的文本被错误地接受.例如:如果我在其中任何一种情况下键入5",结果文本是$5.00",但插入符号位于5"之前,$"之后.如果我尝试输入52.1",我会得到$2.15.00".

the typed text is accepted incorrectly. For example: If I type a '5' in either of these scenarios, the resulting text is "$5.00", but the caret is located before the '5', after the '$'. If I try to type "52.1", I get "$2.15.00".

<Window x:Class="WPF.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="154" Width="240" Name="ThisWindow"
        Background="{StaticResource {x:Static SystemColors.AppWorkspaceBrushKey}}">
    <Grid>
        <TextBox Text="{Binding ElementName=ThisWindow,
                                Path=Amount,
                                StringFormat={}{0:c},
                                UpdateSourceTrigger=PropertyChanged}"
                 VerticalAlignment="Center"
                 HorizontalAlignment="Center"
                 MinWidth="100" />
    </Grid>
</Window>

如果我删除 UpdateSourceTrigger 属性,它会正确输入,但不会保持货币格式.

If I remove the UpdateSourceTrigger attribute, it types correctly, but doesn't maintain the currency format.

有什么想法吗?

推荐答案

这是因为它试图在每个字符按下后应用格式.

This is caused by it trying to apply the formatting after every character press.

作为替代方案,我通常只是设置 TextBox 的样式,因此它只在未编辑时应用格式

As an alternative, I usually just style the TextBox so it only applies formatting when it's not being edited

<Style TargetType="{x:Type TextBox}">
    <Setter Property="Text" Value="{Binding SomeValue, StringFormat=C}" />
    <Style.Triggers>
        <Trigger Property="IsKeyboardFocusWithin" Value="True">
            <Setter Property="Text" Value="{Binding SomeValue, UpdateSourceTrigger=PropertyChanged}" />
        </Trigger>
    </Style.Triggers>
</Style>

这篇关于具有 CurrencyFormat 和 PropertyChanged 触发器的 TextBox 不接受正确的文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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