In Silverlight there is no Enum.Getvalue() method, so there is not out-of-the box way of databinding a radio buttongroup to an enumerable value in a viewmodel.
Step forward converters.
using System;
using System.Windows.Data;
namespace YourNamespace
{ public class EnumBoolConverter : IValueConverter
{ #region Methods
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{ if (value == null || parameter == null)
return value;
return value.ToString() == parameter.ToString();
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (value == null || parameter == null)
return value;
return Enum.Parse(targetType, (String)parameter, true);
}
#endregion Methods
}
}
With the previous convertor it is then quite simple to bind the radio button list. Simply pass the Enum value (as a string) as the converter parameter, and you are away:
<UserControl
...>
<YourNamespace:EnumBoolConverter
x:Key="ConvertEnum" />
<RadioButton
Content="Yes"
GroupName="Group1"
IsChecked="{Binding Path=UserOption, Mode=TwoWay, Converter={StaticResource ConvertEnum}, ConverterParameter=Yes}" />
<RadioButton
Content="No"
GroupName="Group2"
IsChecked="{Binding Path=UserOption, Mode=TwoWay, Converter={StaticResource ConvertEnum}, ConverterParameter=No}" />
<RadioButton
Content="Both"
GroupName="Group3"
IsChecked="{Binding Path=UserOption, Mode=TwoWay, Converter={StaticResource ConvertEnum}, ConverterParameter=Both}" />
Also make sure the GroupName on each radio button is different or the system gets monumentally confused and throws a StackOverflowException.
Leave a Reply