TextBox with CurrencyFormat and PropertyChanged tr

2019-03-06 07:35发布

问题:

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>