WPF文本框格式与绑定

WPF文本框格式与绑定

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

问题描述

我刚刚升级从3.5SP1我们WPF应用程序为4.0。

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

在code下面我们使用文本框底层视图模型绑定。文本框是可编辑的。

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,该格式将其更改为4000。如果用户编辑该值不会发生格式化。

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

使用转换器仍然procudes相同的行为:

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:

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

更新2

与此类似connect文章。

推荐答案

作为更新我把Jonathans建议和rejigged绑定使用引发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文本框格式与绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-12 05:37