Here I will post problems I and my colleagues met and solutions we found.

Sunday, March 01, 2009

Binding to nullable values (WPF)

I don't usually use nullable types, since my approach is to use them only when there is real difference between zero and null values, and it's not often when such difference exists. However, sometimes you may not really know how the value is going to be used. And then having it nullable may be preferable.

That was the case in one of our custom projects. Naturally, you would want to display empty edit box for null value, which was defined as nullable integer. The problem is that by default binding would not handle empty string as null value. Fortunately, with .NET 3.5 SP1 there is a way. You should use TargetNullValue attribute. The binding would look like this then:


{Binding Path=Customer.ClientYear, TargetNullValue={x:Static sys:String.Empty}}

This, and other attributes for the binding collected in one document here

1 comment:

Shimmy said...

I am trying to do the above, but the source is not update with a null value when I clear the target TextBox.