h3mm3's blog

Stories from behind the keyboard

  • RSS
  • Twitter

On a recent demonstration about Silverlight data binding I wanted to bind some RadioButtons in the UI to each possible value of an Enum type; the selected RadioButton would bring the actual value of the enumeration. The following code snippet shows the enumeration.

public enum Sizes
{
Small = 3,
Medium = 4,
Large = 5
}
In the UserControl I configured the various RadioButtons' binding like this:
<!-- XAML Snippet -->
<RadioButton GroupName="SizeGroup"
 IsChecked="{Binding Sizes, Mode=TwoWay, 
 Converter={StaticResource Matcher}, ConverterParameter=Small}">
 ...
</RadioButton>
As you can see I used a custom IValueConverter to make the binding work. The idea was to provide a converter that could check or uncheck the IsChecked property of a RadioButton based on the corresponding enumeration value. You have to pass the ConverterParameter (i.e. "desiredValue") the enumeration value corresponding to the RadioButton. During the binding, the Convert(..) method returns true if the bound property value matches the desiredValue, otherwise it returns false. When the user change the checked status of a RadioButton, the ConvertBack(..) method returns the enumeration value to the bound property, if the RadioButton is checked, otherwise nothing happens (!). Here follows the IValueConverter implementation (note that this converter can be used with any enum type).
<!-- Custom IValueConverter -->
public class MatchingEnumConverter : IValueConverter
{
 public object Convert(object value, Type targetType, 
  object desiredValue, CultureInfo culture)
 { 
  return Enum.Parse(
   value.GetType(), 
   desiredValue.ToString(), 
   true).Equals(value);
 }

 public object ConvertBack(object value, Type targetType, object desiredValue,    CultureInfo culture)
 {
  return (bool)value ? desiredValue : null;
 }
}
Of course I registered the converter among the Resources of the UserControl, using the x:Key="Matcher".

1 comment:

Anonymous said...

thanks!