处理空的数字绑定

本文关键字:绑定 数字 处理 | 更新日期: 2023-09-27 18:19:53

我的视图模型中有一个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将值更改为一些预定义的默认值,这在我的情况下不适用。

处理空的数字绑定

其中一种方法是使用控制,设计用于处理数字,如IntegerUpDown:

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

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

您可以尝试使用绑定的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}" />

这是假设您希望值在为空时为零。

您尝试过转换器吗?它可以让你对这个值为所欲为,当它明确时,你可以将它设置为你选择的默认值。

这是本文中的一个示例:

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 }}" 
/>

试试这个:

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