TextBox with CurrencyFormat and PropertyChanged trigger doesn't accept text right

情到浓时终转凉″ 提交于 2019-12-04 05:22:42

问题


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. The TextBox is empty, or
  2. All of the text is selected,

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>

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

Any ideas?


回答1:


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

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>


来源:https://stackoverflow.com/questions/9910681/textbox-with-currencyformat-and-propertychanged-trigger-doesnt-accept-text-righ

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!