【问题标题】:Wpf textbox converter to double in combination with updatesourcetrigger=propertychangedWpf 文本框转换器结合 updatesourcetrigger=propertychanged 加倍
【发布时间】:2013-02-11 09:11:48
【问题描述】:

在我们的项目中,我们有一个绑定到双精度的 WPF 文本框。有一个转换器允许在转换回中例如同时使用“.”。和“,”作为小数点,并在转换方法中将双精度格式化为 n2 数字格式。 在这里您可以看到我们转换器的简化版本:

public class DoubleConverter:IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        if (value == null || value.GetType() != typeof(double))
            return null;
        else
            return ((double)value).ToString("n2");
    }


    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        if (value == null)
           return null
        else
             return Double.Parse(((string)value).Replace('.',','));
    }
}

文本框如下所示:

        <TextBox  Text="{Binding Path=Factor, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged, ValidatesOnDataErrors=True}" Width="500" Height="50" />

并且双属性引发了一个propertychanged事件:

public double Factor
    {
        get { return _factor; }
        set
        {
            _factor = value;
            if (PropertyChanged != null)
                PropertyChanged(this, new PropertyChangedEventArgs("Factor"));
        }
    }

这在以前版本的 WPF 中可以正常工作,因为在输入文本时没有调用转换。这种行为显然已经改变,现在在每个文本条目上调用转换方法,导致在您键入内容时对双精度进行格式化。即使您不使用格式化,您也会遇到无法输入小数点的问题。

这可以通过不使用 UpdateSourceTrigger=Propertychanged 来解决,但我们需要它来进行验证。我们使用 IDataErrorInterface 实现验证。我知道有一个ValidateWithoutUpdate method,但这不适用于使用 IDataErrorInterface 进行验证。

所以我基本上需要的是 ConvertBack(以及验证)发生 OnPropertyChanged 和 Convert 只发生 OnLostFocus。
这可能吗?或者我们的问题有其他解决方案吗?

【问题讨论】:

    标签: wpf validation binding textbox updatesourcetrigger


    【解决方案1】:

    是的,行为从 .Net 3.5 更改为 .Net 4.0,它现在将源更新发送回目标,即使更新源自目标。这篇 SO 帖子稍微解释了一下并提供了解决方案:

    Why does binding setup behave differently in .NET 4 vs .NET 3.5

    这些是我迄今为止找到的处理这个问题的选项:

    • 让转换器保持 ConvertBack 上的输入状态并在 Convert 中恢复它(建议在上面的链接中)
    • 将支持数据更改为字符串,在模型中处理转换
    • 创建一个处理这种数字输入的自定义控件,类似于 DateTimePicker 的工作方式(它维护数据的字符串和双精度表示;显示字符串,但受双精度约束)

    【讨论】:

    • 谢谢,我最终制作了一个自定义控件;)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-03
    • 1970-01-01
    • 2010-12-29
    相关资源
    最近更新 更多