WPF 文本框绑定格式 [英] WPF TextBox Binding with Formatting

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

问题描述

我刚刚将 wpf 应用程序从 3.5sp1 升级到 4.0.

I have just upgraded our wpf application from 3.5sp1 to 4.0.

我们使用下面的代码将文本框绑定到底层视图模型.文本框是可编辑的.

The code below we use to bind the textbox to the underlying view model. The textbox is editable.

    <TextBox HorizontalContentAlignment="Right"
Text="{Binding Path=Price,   StringFormat={0:#,##0;(#,##0)},  Mode=TwoWay,  ValidatesOnDataErrors=True,  UpdateSourceTrigger=PropertyChanged, ValidatesOnExceptions=True}"/>

在 3.5sp1 中,格式化只会在最初发生.因此,当加载文本框并绑定到值 4000 时,格式会将其更改为 4,000.如果用户编辑此值,则不会发生格式设置.

In 3.5sp1 the formatting would only occur initially. So when the textbox was loaded and bound to value 4000, the formatting would change it to 4,000. If user edited this value no formatting would occur.

在 4.0 中,格式随着值的变化而发生(即当用户输入新值时).虽然理论上这听起来不错,但实际上这是一场灾难.光标到处都是.它无法使用.

In 4.0 the formatting occurs as the value changes (ie while user enters in new value). While in theory this sounds OK, in reality its a disaster. The cursor is all over the place. Its unusable.

现在,我们可以将 UpdateSourceTrigger 更改为LostFocus",但这会导致在某些情况下无法验证数据的新问题.

Now, we could change the UpdateSourceTrigger to "LostFocus" but that introduces new problems with data not being validated in certain scenarios.

有没有办法恢复旧的 3.5sp1 行为?

Is there a way to get the old 3.5sp1 behaviour back?

更新 1

使用 Converter 仍会产生相同的行为:

Using Converter still procudes same behaviour:

public class DecimalConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (value != null)
            return ((decimal)value).ToString("#,##0;(#,##0)");

        return string.Empty;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return value;
    }
}

和修改后的 XAML:

and the modified XAML:

<TextBox Text="{Binding Path=Price, Converter={StaticResource DecimalConverter}, Mode=TwoWay, ValidatesOnDataErrors=True, UpdateSourceTrigger=PropertyChanged, ValidatesOnExceptions=True}"/>

更新 2

类似于这个 连接文章.

推荐答案

作为更新,我采纳了 Jonathans 的建议,并重新调整了 Binding 以使用 LostFocus 而不是 PropertyChanged(在适当的情况下 - 即也指定了 StringFormat 的任何地方).

As an update I took Jonathans suggestion and rejigged the Binding to use LostFocus instead of PropertyChanged (where appropriate - ie wherever StringFormat was also specified).

正如乔纳森所说,在某些情况下,您必须采用这种方法手动触发绑定刷新/验证.

As Jonathan said, in some cases you have to trigger binding refresh / validation manually taking this approach.

如果有人有更好的方法,我很乐意看到.

If anyone has better approach, I would love to see it.

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

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