用的StringFormat在一个文本框绑定到一个双 [英] Binding to a double with StringFormat on a TextBox

查看:204
本文介绍了用的StringFormat在一个文本框绑定到一个双的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用WPF的文本框上的Text属性双重我的视图模型绑定。

I am using WPF's TextBox with a binding on the Text property to a double on my ViewModel.

我的XAML看起来是这样的:

My XAML looks like this:

<TextBox Text="{Binding Path=MyDoubleValue, StringFormat=N2, UpdateSourceTrigger=PropertyChanged}" />

不幸的是,当我切换UpdateSourceTrigger到的PropertyChanged和类型值 12345 ,我得到 12,354.00 修改:注意5的4之前)。这是在 2 保持光标在同一个地方后添加的结果3 由.NET格式。

Unfortunately when I switch UpdateSourceTrigger to PropertyChanged and type value 12345, I get 12,354.00 (EDIT: notice the 5 before the 4). This is a result of keeping cursor in the same place after adding , between 2 and 3 by the .NET formatter.

我如何使用的StringFormat与UpdateSourceTrigger设置的PropertyChanged?

How can I use StringFormat with UpdateSourceTrigger set to PropertyChanged?

请注意:这只是发生在.NET 4

Note: This is only happening in .NET 4.

推荐答案

通常你不想 UpdateSourceTrigger 的PropertyChanged TextBox.Text 结合,因为这会触发验证和每一次的关键是pressed更改通知。

Usually you don't want UpdateSourceTrigger to be PropertyChanged on a TextBox.Text binding because this triggers the Validation and Change notification every time a key is pressed.

如果你正在做这个只有这样,如果用户点击回车,将保存值之前处理save命令,那么我建议挂钩到 previewKeyDown 事件,并手动更新源,如果pssed关键$ P $是输入(通常我做这一个AttachedProperty)

If you are doing this only so that if the user hits Enter it will save the value before processing the save command, then I'd suggest hooking into the PreviewKeyDown event and manually updating the source if the key pressed was Enter (Usually I make this an AttachedProperty)

private void TextBox_PreviewKeyDown(object sender, KeyEventArgs e)
{
    if (e.Key == Key.Enter)
    {
        var obj = sender as UIElement;
        BindingExpression textBinding = BindingOperations.GetBindingExpression(
            obj, TextBox.TextProperty);

        if (textBinding != null)
            textBinding.UpdateSource();
    }
}

不过,他这样说,如果你仍然想使用 UpdateSourceTrigger =的PropertyChanged ,然后再考虑显示值时使用的格式,但将其删除,而用户正在编辑吧。

But with that being said, if you still wanted to use UpdateSourceTrigger=PropertyChanged, then consider using the formatting when displaying the value, but remove it while the user is editing it.

<TextBox>
    <TextBox.Style>
        <Style TargetType="{x:Type TextBox}">
            <Setter Property="Text" Value="{Binding Path=MyDoubleValue, StringFormat=N2}" />
            <Style.Triggers>
                <Trigger Property="IsFocused" Value="True">
                    <Setter Property="Text" Value="{Binding Path=MyDoubleValue, UpdateSourceTrigger=PropertyChanged}" />
                </Trigger>
            </Style.Triggers>
        </Style>
    </TextBox.Style>
</TextBox>

这篇关于用的StringFormat在一个文本框绑定到一个双的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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