XAML Nullable Bindings

by CoderForRent 17. November 2009 06:10

A buddy and I found out today that binding to Nullable properties in XAML is a bit trickier than you may at first expect.  Everything works fine until you try to remove all of the text from a bound textbox.  What we were expecting is that the underlying value of the bound property would get set to null, but in fact the value doesn't get changed at all.  This is because the Binding engine cannot set it to null, because string.Empty isn't actually null, so it just ignores the binding.

 

A simple solution is to create a converter that can look for these situations and handle it as expected.

 

public class NullableConverter : IValueConverter
{

public object Convert(object value, Type targetType, object parameter, CultureInfo culture)

     return value;

}

public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{

     if (value == null || string.IsNullOrEmpty(value.ToString()))
         return null;

     return value;

}

}

 

 

Tags: , , ,