gre*_*nis 1 wpf binding textbox currency string-formatting
我TextBox在一个WPF窗口中绑定了一个类型窗口的依赖属性double(见下文).每当用户键入TextBox时
TextBox是空的,或键入的文本被错误地接受.例如:如果我在这些场景中输入'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>
Run Code Online (Sandbox Code Playgroud)
如果我删除UpdateSourceTrigger属性,它会正确键入,但不保持货币格式.
有任何想法吗?
这是因为它在每次按下字符后尝试应用格式.
作为替代方案,我通常只是设置样式,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>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3221 次 |
| 最近记录: |