WPF DataBinding:Nullable Int仍然出现验证错误?

m-y*_*m-y 47 c# data-binding validation wpf

我通过代码将文本框数据绑定到可以为空的int.如果我从文本框中删除数据,它会给我一个验证错误(它周围的红色边框).

这是我的绑定代码:

ZipBinding = new Binding("Zip");
ZipBinding.Source = Address;
zipTextBox.SetBinding(TextBox.TextProperty, ZipBinding);

public Int32? Zip { get { ... } set { ... } }
Run Code Online (Sandbox Code Playgroud)

它清楚地标记为Nullable,那么为什么当我清除文本框时WPF想给我一个验证问题?

Qua*_*ter 89

验证失败,因为它无法将空字符串转换为可以为空的整数.在绑定上将 TargetNullValue 设置为string.empty,它会将空字符串转换为null,这将是有效的.

  • 效果很好!有关如何在XAML http://stackoverflow.com/a/1895482/83111中执行此操作,请参阅此答案 (24认同)
  • @Beauty你可以把它设置为string.Empty:`<TextBox Text ="{Binding MyNumericProperty,TargetNullValue = {x:Static system:String.Empty}}"/>`(包括UserControl头部的系统:`xmlns :系统= "CLR-命名空间:系统;装配= mscorlib程序"`).这与将其设置为值为"string.Empty"的字符串不同...就像有人告诉你将字符串设置为null,你不做`username ="null";`. (2认同)