Thursday, July 10, 2014

Problem when two-way binding radio buttons using a converter

In an earlier post I showed how to use a converter to bind radio buttons but I made a subtle error in the ConvertBack code that caused havoc.

Here is the ConvertBack method as I originally wrote it.

Public Function ConvertBack(value As Object, targetType As System.Type, parameter As Object, culture As System.Globalization.CultureInfo) As Object Implements System.Windows.Data.IValueConverter.ConvertBack ' Return the parameter if the button is checked If value Is Nothing Or parameter Is Nothing Then Return Nothing End If Dim IsChecked As Boolean = False Boolean.TryParse(value, IsChecked) If IsChecked Then Return parameter Else Return Nothing End If End Function
The symptoms were that occasionally the source of the binding was being set to DBNull and saved to the database. It should always be "1" or "2".

After much head-scratching and cursing of Microsoft I noticed the problem occurred when I checked the first radio button in the group.

This causes the ConvertBack method to be called for the first radio button with a parameter of "1". Because the radio button is checked the ConvertBack method returns "1" and the source is set to "1".

Then the ConvertBack method is called for the second radio button with a parameter of "2". Because the second radio button is not checked the ConvertBack method returns nothing which causes the source to be set to DBNull.

The solution is to change both "Return Nothing" lines to "Return DependencyProperty.UnsetValue". This tells the framework not to change the source value, which leaves it as "1".

No comments:

Post a Comment