WPF DataBinding: Nullable Int still gets a validation error?

C#WpfValidationData Binding

C# Problem Overview


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?

C# Solutions


Solution 1 - C#

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.

Solution 2 - C#

An empty TextBox != null.

You may have to tweak the ValidationRule to accommodate empty strings as entries. Or, you could create a converter to take empty strings and convert them to null.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionmyermianView Question on Stackoverflow
Solution 1 - C#QuartermeisterView Answer on Stackoverflow
Solution 2 - C#Eric OlssonView Answer on Stackoverflow