2012-03-28 34 views
0

我有一个TextBox在WPF窗口绑定到类型double(见下文)的窗口的依赖项属性。每当在TextBox用户类型时具有CurrencyFormat和PropertyChanged触发器的TextBox不接受文本权

  1. TextBox是空的,或
  2. 所有的文字被选中,

键入的文本被错误地接受。例如:如果在这两种情况下都输入'5',则结果文本为“$ 5.00”,但插入符号位于“$”之后的“5”之前。如果我尝试输入“52.1”,我会得到“$ 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属性,它的类型正确,但不保持货币格式。

任何想法?

+0

使用转换器的格式。 TextBox实际上只处理文本,当你绑定到文本以外的东西时,它必须做出一些假设(猜测)。 http://stackoverflow.com/questions/9050054/cannot-assign-a-null-value-to-a-nullable-int32-via-binding – Paparazzi 2012-03-28 15:29:16

回答

5

这是由于它试图在每次按下字符后应用格式。

作为替代,我通常只是风格的TextBox所以只适用于当它没有被编辑

<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> 
+0

这就是我的意思是在我的问题结束时,当我说删除更新触发器不保持格式。我正在构建一个会计应用程序,如果可以的话,我想保留格式。 – gregsdennis 2012-03-28 16:17:39

+0

@gregsdennis此风格将保持货币格式,但仅当用户不关注'TextBox'时。一旦用户点击“TextBox”,它将摆脱格式并显示数字。在“TextBox”中键入仍然会在每个键击中触发一个“PropertyChanged”事件,但在键入时不会尝试格式化数字。 – Rachel 2012-03-28 16:23:46

+0

我明白了。我想保持格式,而用户在框中键入。 – gregsdennis 2012-03-28 16:26:29

相关问题