【问题标题】:WPF Binding with invalid value for source源值无效的 WPF 绑定
【发布时间】:2011-01-18 13:12:47
【问题描述】:

我有一个绑定到整数属性的TextBox

TextBox 中没有任何有效文本时,我该怎么做才能将该属性设置为 0。

真的,我认为这可以扩展,如果绑定失败,我们将源设置为默认(T)。

我需要朝着正确的方向轻推。

TargetNullValue 与我正在寻找的相反(我认为),它在源为空时设置 TextBox 文本。我想在TextBox 文本是无效绑定值时将源设置为其默认值。

【问题讨论】:

    标签: wpf data-binding binding textbox


    【解决方案1】:

    Converter 应用到您的绑定中应该可以解决问题:

    public class TextConverter : IValueConverter
    {
        public object Convert(object value, Type targetType,
            object parameter, CultureInfo culture)
        {
            int actual = (int)value;
    
            return actual.ToString();
        }
    
        public object ConvertBack(object value, Type targetType,
            object parameter, CultureInfo culture)
        {
            string actual = (string)value;
    
            int theValue = 0;
            int.TryParse(actual, out theValue);
    
            return theValue;
        }
    }
    

    您的TextBox 绑定看起来像这样:

    <TextBox Text="{Binding ... Converter={StaticResource convert}}"></TextBox>
    

    将转换器定义为 Window/Control/...的资源...

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-07-11
      • 2016-01-12
      • 1970-01-01
      • 2010-10-13
      • 2010-10-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多