#358 – Binding a RadioButton to an Enumerated Type

You can bind RadioButton controls to an enum by using a value converter.

The XAML:

    <Window.Resources>
        <loc:EnumToBooleanConverter x:Key="enumToBooleanConverter" />
    </Window.Resources>

    <StackPanel HorizontalAlignment="Center" Margin="15">
        <Label Content="Favorite animated character?"/>
        <RadioButton IsChecked="{Binding Path=FavCharacter, Converter={StaticResource enumToBooleanConverter}, ConverterParameter={x:Static loc:CartoonCharacters.Gumby}}"
                     Content="Gumby"/>
        <RadioButton IsChecked="{Binding Path=FavCharacter, Converter={StaticResource enumToBooleanConverter}, ConverterParameter={x:Static loc:CartoonCharacters.PinkPanther}}"
                     Content="Pink Panther"/>
        <RadioButton IsChecked="{Binding Path=FavCharacter, Converter={StaticResource enumToBooleanConverter}, ConverterParameter={x:Static loc:CartoonCharacters.Magoo}}"
                     Content="Mr. Magoo"/>
    </StackPanel>

The enumeration:

    public enum CartoonCharacters
    {
        Gumby,
        PinkPanther,
        Magoo
    }

The enum-based property you’re binding to:

        public CartoonCharacters FavCharacter { get; set; }

And the value converter referenced by the XAML:

    public class EnumToBooleanConverter : IValueConverter
    {
        // Convert enum [value] to boolean, true if matches [param]
        public object Convert(object value, Type targetType, object param, CultureInfo culture)
        {
            return value.Equals(param);
        }

        // Convert boolean to enum, returning [param] if true
        public object ConvertBack(object value, Type targetType, object param, CultureInfo culture)
        {
            return (bool)value ? param : Binding.DoNothing;
        }
    }
Advertisements