【问题标题】:Texbox to number binding文本框到数字绑定
【发布时间】:2012-06-07 18:50:09
【问题描述】:

我正在使用 WatermarkTextBox 并将其值绑定到 View Model 整数属性。问题是:我需要如果没有设置值,那么WatermarkTextBox 必须显示水印,但是,考虑到它在没有设置值时绑定到整数(比如显示视图时),那么它显示 0。

我不能使用OneWayToSource,因为我需要双向绑定。有什么想法吗?

【问题讨论】:

    标签: wpf data-binding mvvm wpf-controls wpftoolkit


    【解决方案1】:

    您可以使用转换器。如果值为 0,则转换器返回一个空字符串,使水印可见。如果不为 0,则返回数字的字符串表示形式。

    public class Int32ToStringConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            int v = (int)value;
            if (v == 0)
                return string.Empty;
            return v.ToString();
        }
    
        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            string s = (string)value;
            if (string.IsNullOrEmpty(s))
                return 0;
            return int.Parse(s);
        }
    }
    

    另一种选择是将属性更改为int? (Nullable<int>),并将其初始值设置为null。

    【讨论】:

    • Tomas 您的解决方案有效,但现在当输入不是数字时,它会引发异常(我知道是 ConvertBack 中的 int.Parse(s),但是,事情是这样的。正如它来了,当转换失败时,文本框边框变为红色(我想它与转换错误通知有关)是的。是否可以通知发件人 - 在这种情况下是文本框 - 转换失败,或者,我该如何管理用户输入字符串而不是数字时的情况?谢谢
    • 算了,写了个正则表达式。感谢 public object ConvertBack( object value, Type targetType, object parameter, CultureInfoculture) { string s = (string)value; if (string.IsNullOrEmpty(s)) 返回 0; s = Regex.Replace(s, "[^0-9]", "");返回 int.Parse(s); }
    猜你喜欢
    • 2016-08-28
    • 1970-01-01
    • 2012-04-20
    • 1970-01-01
    • 2013-07-13
    • 1970-01-01
    • 2017-04-07
    • 2010-12-02
    • 1970-01-01
    相关资源
    最近更新 更多