#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;
        }
    }
About these ads

About Sean
Software developer in the Twin Cities area, passionate about .NET technologies. Equally passionate about my own personal projects related to family history and preservation of family stories and photos.

3 Responses to #358 – Binding a RadioButton to an Enumerated Type

  1. Pingback: Dew Drop – August 5, 2011 | Alvin Ashcraft's Morning Dew

  2. Pingback: İpinUcu ~ 77 ~ WPF’te RadioButton Kullanımı « Mehmet KAPLAN

  3. qsb says:

    worked great!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 234 other followers

%d bloggers like this: