文本框与CurrencyFormat并触发的PropertyChanged不接受正确的文本 [英] TextBox with CurrencyFormat and PropertyChanged trigger doesn't accept text right

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

问题描述

我绑定到类型的窗口的依赖属性WPF窗口有一个文本框 双击(见下面)。每当用户类型的文本框

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. 文本框为空或

  2. 所有的文字被选中,

键入的文本被错误地接受。例如:如果我在任何一种情况输入5,由此产生的文本是$ 5.00,但插入符位于前5中,$之后。如果我尝试输入52.1,我得到$ 00年2月15日。

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.

任何想法?

推荐答案

这是由它试图每个字符preSS后应用格式造成的。

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>

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

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