Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF Textbox remove currency formatting on focus

Tags:

wpf

Is it possible to remove the currency formatting on a WPF textbox on focus? The app follows MVVM.

<TextBox HorizontalAlignment="Left"
         Height="23"
         Margin="156,264,0,0"
         TextWrapping="Wrap"
         HorizontalContentAlignment="Right"
         Text="{Binding Amount, StringFormat=c, ValidatesOnNotifyDataErrors=True}"
         VerticalAlignment="Top"
         Width="100" />

I need the formatting while the textbox is not having focus. But it needs to be removed only when it having focus to enable easy editing by the user. The reason for removing the $ is that when you tab, the focus is before the $. This means the user has to click again or use the arrow key to move to the digits.

When the user tabs to the above textbox the currency symbol should be removed. Thanks for your help.

like image 496
isakavis Avatar asked May 20 '13 18:05

isakavis


1 Answers

You can write trigger that will be executed when TextBox is focused and at the moment you can change StringFormat.

TextBox style:

<TextBox TextWrapping="Wrap"
         Height="23" Width="200" 
         HorizontalAlignment="Left" HorizontalContentAlignment="Right" VerticalAlignment="Top">
    <TextBox.Style>
        <Style TargetType="TextBox">                   
            <Setter Property="Text" Value="{Binding Amount, StringFormat=C, UpdateSourceTrigger=LostFocus}" />
            <Style.Triggers>
                <Trigger Property="Control.IsFocused" Value="True">
                    <Setter Property="Text" Value="{Binding Amount, StringFormat=F2, UpdateSourceTrigger=LostFocus}" />                            
                </Trigger>
            </Style.Triggers>
        </Style>
    </TextBox.Style>
</TextBox>
like image 80
kmatyaszek Avatar answered Sep 24 '22 12:09

kmatyaszek