处理空数字绑定

时间:2015-10-29 09:55:34

标签: c# wpf data-binding

我的View-Model中有一个WPF属性int属性,如下所示:

private int _port;
public int Port
{
    get { return _port; }
    set { SetProperty(ref _port, value); }
}

我的观点是这样的:

<TextBox Text="{Binding Port, UpdateSourceTrigger=PropertyChanged}" />

我的问题是,每当用户清除文本框文本时,我都会收到以下错误:

  

无法转换价值。

这会导致绑定不更新属性,因此我为命令CanExecute逻辑设置的任何规则都不适用。
有没有办法覆盖此行为(不将属性的类型更改为Nullable)?

更新
我已经尝试使用FallbackValue或转换器,但是这个2将值更改为某个预定义的默认值,这在我的情况下不适用。

4 个答案:

答案 0 :(得分:1)

您可以尝试使用Binding的FallBackValue。

请参阅https://msdn.microsoft.com/en-us/library/system.windows.data.bindingbase.fallbackvalue%28v=vs.110%29.aspx

像这样的迁移工作:

<TextBox Text="{Binding Port, FallBackValue="0", UpdateSourceTrigger=PropertyChanged}" />

假设您希望空值时该值为零。

答案 1 :(得分:0)

其中一种方法是使用旨在处理数字的控件,例如IntegerUpDown

<xctk:IntegerUpDown Value="{Binding MyValue}"/>

另一种方法是编写IValueConverter以用于绑定。

答案 2 :(得分:0)

你试过转换器吗? 它会让你随心所欲地做任何事情,当它清楚时,你可以将它设置为你选择的默认值。

以下是此article的示例:

class IntConverter : IValueConverter
{
  /// <summary>
  /// should try to parse your int or return 0 otherwise.
  /// </summary>
  public object Convert(object value,Type targetType,object parameter,CultureInfo culture)
  {
    int temp_int;
    return (Int32.TryParse(value, out temp_int)
       ? temp_int
       : 0;
  }

  public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
  {
    throw new NotImplementedException();
  }
}  

要使用上述转换器,请在Xaml中使用:

<TextBox Text="{Binding Port, 
                UpdateSourceTrigger=PropertyChanged}",
                Converter={StaticResource IntConverter }}" 
/>

答案 3 :(得分:-1)

试试这个:

public int Port
{
    get { return _port; }
    set { SetProperty(ref _port, string.IsNullOrWhitespace(value.ToString())?0 :value); 
}