无法为Nullable Int32分配空值? 通过绑定

无法通过TextBox绑定到Int32?分配空值。 如果TextBox为空,则不调用Int32Null Set。
TexBox周围有一个红色边框,表示validationexception。

这只是Int32没有意义吗? 是可以为空的。 如果用户从TextBox中删除整数值,我希望调用Set,以便将属性赋值为null。

当它启动int32Null = null并且TextBox不是红色时。

我尝试实现validation,如果TextBox为空,则设置validation = true。 但仍未调用Set,TextBox为红色,表示validation错误。

看起来我应该能够通过绑定为空值分配空值。

             
  public partial class MainWindow : Window { private Int32? int32Null = null; private string stringNull = "stringNull"; public MainWindow() { InitializeComponent(); } public Int32? Int32Null { get { return int32Null; } set { int32Null = value; } } public string StringNull { get { return stringNull; } set { stringNull = value; } } } 

设置StringNull会被调用,传递的值不是null,而是string.empty。

由于在Int32Null上没有调用Set,我不知道传递了什么。

它还将一个string.empty传递给Int32?。 不得不将空字符串转换为null。

  [ValueConversion(typeof(Int32?), typeof(String))] public class Int32nullConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { Int32? int32null = (Int32?)value; return int32null.ToString(); } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { string strValue = value as string; if(string.IsNullOrEmpty(strValue.Trim())) return null; Int32 int32; if (Int32.TryParse(strValue, out int32)) { return int32; } return DependencyProperty.UnsetValue; } } 

你对类型转换器应该如何处理它做出错误的假设。 因此,如果他们没有做你想做的事情,即将空字符串转换为null你要么必须自己编写,要么使用为你进行转换的Binding.Converter