#358 – Binding a RadioButton to an Enumerated Type
August 5, 2011 4 Comments
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; } }
Pingback: Dew Drop – August 5, 2011 | Alvin Ashcraft's Morning Dew
Pingback: İpinUcu ~ 77 ~ WPF’te RadioButton Kullanımı « Mehmet KAPLAN
worked great!
The only problem with this is there’s no defense against the user clicking the selected toggle button. It will appear to turn itself off even though the bound value is correct for that button. To fully make it work consistently you either need to turn IsHitTestVisible off when IsChecked is true or do something fancier with a multivalueconverter or something.