【问题标题】:Dealing with empty numeric bindings处理空数字绑定
【发布时间】:2015-10-29 09:55:33
【问题描述】:

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

【问题讨论】:

标签: c# wpf data-binding


【解决方案1】:

其中一种方式是使用控制,专为处理数字而设计,如IntegerUpDown

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

另一种方法是写IValueConverter在绑定中使用。

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

    • 注意类型是int所以你应该做FallBackValue=0
    • 这不会改变结果(在应用@M.kazemAkhgary 建议时)
    • 您可能还需要将它与 TargetNullValue 结合起来才能使其工作。试试 TargetNullValue={x:Static sys:String.Empty}
    • 还是一样。我猜TargetNullValue 没有效果,因为我的属性不是 Nullable
    【解决方案3】:

    你试过转换器吗? 它会让你对这个值做任何你想做的事情,当它清楚时,你可以将它设置为你选择的默认值。

    这是来自 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 }}" 
    />
    

    【讨论】:

      【解决方案4】:

      试试这个:

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

      【讨论】:

      • string.IsNullOrWhitespace(value.ToString()) 没有多大意义。因为int 是一个值类型,并且总是有一些值,所以ToString 永远不会返回nullstring.Empty。此外,当绑定转换失败时,绑定引擎不会调用属性设置器。
      猜你喜欢
      • 2014-01-26
      • 1970-01-01
      • 1970-01-01
      • 2017-07-18
      • 2018-10-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多