WPF Binding to nullable types

WPF binding can be confusing.  There are still times where I encounter a problem that I have no idea how to solve.  Thanks to Google I usually find my solution.

Today I was working with binding on a text field to a nullable double property.  Consider the following situation: My textbox and property both start out with a valid double value.  Then I delete everything from the textbox.  At the point my setter should fire for the property it sees an empty string and doesn’t assign any value because my property is a double.  So how do you actually get that to recognize that is should change the property to null?

Thanks to Maxim Alexeyev’s Discoverting .NET blog I was able to find the easy solution.

Add TargetNullValue to your binding.  Now my binding looks like this.

Text=”{Binding SomeNullableDoubleProperty, TargetNullValue={x:Static System:String.Empty}}”

This makes sure that anytime my textbox sees a String.Empty it knows to treat that as a null. When I remove any value from the textbox a null value is set to my nullable double type and everyone is happy!