代码之家  ›  专栏  ›  技术社区  ›  Jose

具有无效源值的WPF绑定

  •  2
  • Jose  · 技术社区  · 14 年前

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

    如果没有有效的文本, 文本框 属性设置为0。

    实际上,我认为这可以扩展,这样如果绑定失败,那么我们就将源设置为默认值(T)。

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

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

    1 回复  |  直到 13 年前
        1
  •  4
  •   Dave Clemmer manu    13 年前

    应用一 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>
    

    将转换器定义为窗口/控件的资源。