Reputation: 3442
This is my Enum structure:
namespace MyNS
{
enum MyEnum
{
MyValOne = 1,
MyValTwo = 2
}
}
Instead of this:
<RadioButton x:Name="1" />
<RadioButton x:Name="2" />
I want something like this: (The x:Name attribute is not important. Any attribute is ok)
<RadioButton x:Name="MyNS.MyEnum.MyValOne" />
<RadioButton x:Name="MyNS.MyEnum.MyValTwo" />
How can I do this?
Upvotes: 2
Views: 713
Reputation: 39006
You just need an enum converter like this.
public class EnumRadioButtonConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, string language)
{
return value.ToString() == parameter.ToString();
}
public object ConvertBack(object value, Type targetType, object parameter, string language)
{
return (bool)value ? Enum.Parse(typeof(MyEnum), parameter.ToString(), true) : null;
}
}
And this is how you use it (don't forget to give them a GroupName
). You will need to define a SelectedEnum
property (of type MyEnum
) in your viewmodel of course.
<RadioButton IsChecked="{Binding SelectedEnum, ConverterParameter=MyValTwo, Converter={StaticResource EnumRadioButtonConverter}, Mode=TwoWay}" GroupName="MyRadioButtonGroup" />
<RadioButton IsChecked="{Binding SelectedEnum, ConverterParameter=MyValOne, Converter={StaticResource EnumRadioButtonConverter}, Mode=TwoWay}" GroupName="MyRadioButtonGroup" />
To use the converter, you need to reference it in your resource section.
<Page.Resources>
<local:EnumRadioButtonConverter x:Key="EnumRadioButtonConverter" />
Please find a working sample here.
Upvotes: 3