XAML Nullable Bindings

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;
}
}

blog comments powered by Disqus

Custom Development

ALL USA BASED DEVELOPERS

 

Coder For Rent is a one-stop shop for all your .Net programming needs.  We can make project-based fixed bids as well as hourly/weekly/monthly quotes.  Our goal is to meet your needs the first time, saving you time and money.

 

Call to speak with an account manager. We take projects of all sizes.

 

713-482-7155 

Contact Us

Call 713-482-7155 
for technical or purchasing support

Freshbooks Rocks

FreshBooks

Silverlight Gantt Chart Control
Silverlight Scheduler Control