54

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?

myermian
  • 31,823
  • 24
  • 123
  • 215

2 Answers2

104

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.

Quartermeister
  • 57,579
  • 7
  • 124
  • 111
  • 28
    Works great! See this answer for how to do it in XAML http://stackoverflow.com/a/1895482/83111 – Oskar Jan 04 '12 at 20:58
  • 1
    Don't set it to String.Empty, because then you see the text "String.Empty" in the field for null values in the model. Use an empty String instead. Example: `` – Beauty Jun 13 '17 at 12:17
  • 4
    @Beauty you can set it to string.Empty: `` (including system at the header of the UserControl: `xmlns:system="clr-namespace:System;assembly=mscorlib"`). This is different to setting it to a string whose value is "string.Empty"... much like when someone tells you to set a string to null, you don't do `username = "null";`. – ANeves Apr 04 '18 at 13:57
0

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.

Eric Olsson
  • 4,805
  • 32
  • 35
  • So it's failing because it's trying to parse String.Empty into an Int32? ... If that's the case then yea, I guess I'll have to create a StringEmpty to Null Converter. – myermian Jul 21 '10 at 18:20