zl程序教程

您现在的位置是:首页 >  后端

当前栏目

WPF DataBinding: Nullable Int still gets a validation error?

WPF Error int validation DataBinding
2023-09-11 14:14:17 时间

WPF DataBinding: Nullable Int still gets a validation error?

I have a textbox databound to a nullable int through code. If I erase the data from the textbox it gives me a validation error (red border around it).

Here is my binding code:

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

public Int32? Zip { get { ... } set { ... } }

It's clearly marked as a Nullable so why does WPF wanna give me a validation issue when I clear the textbox?

 

回答1

Validation is failing because it can't convert the empty string to a nullable integer. Set TargetNullValue to string.empty on the Binding and it will convert the empty string to null, which will be valid. 

评论

Works great! See this answer for how to do it in XAML stackoverflow.com/a/1895482/83111
– Oskar
Jan 4, 2012 at 20:58
 
 
 
 

Set value to null in WPF binding

please take a look at the following line

<TextBox Text="{Binding Price}"/>

This Price property from above is a Decimal? (Nullable decimal).

I want that if user deletes the content of the textbox (i.e. enters empty string, it should automatcally update source with null (Nothing in VB).

Any ideas on how I can do it 'Xamly'?

 

回答1

I am using .NET 3.5 SP1 so it's very simple:

<TextBox Text="{Binding Price, TargetNullValue=''}"/>

Which stands for (thanks Gregor for your comment):

<TextBox Text="{Binding Price, TargetNullValue={x:Static sys:String.Empty}}"/>

sys is the imported xml namespace for System in mscorlib:

xmlns:sys="clr-namespace:System;assembly=mscorlib"

Hope that helped.