SyntaxHighlighter

Tuesday, November 15, 2011

Binding an Enum to radiobuttons

I have a WPF project that uses radio buttons to exclusively choose between three options. There was a lot of code to decide which radio was pushed. Thanks to a blog post by Todd Davis, I got binding working on the radio buttons.
Suppose you have an Enum that corresponds to your radio buttons, and then set up a dependency property on it.

public enum KmlFileTypes
{
Simple,
Slider,
Splits
}

public static readonly DependencyProperty MkftProperty =
DependencyProperty.Register("Mkft",
typeof(KmlFileTypes),
typeof(MainWindow));

public KmlFileTypes Mkft
{
get { return (KmlFileTypes)GetValue(MkftProperty); }
set { SetValue(MkftProperty, value); }
}

The binding works because of a enum to boolean converter:
public class EnumToBooleanConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return (value.ToString() == parameter.ToString());
}

public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return (bool)value ? Enum.Parse(targetType, parameter.ToString(), true) : null;
}
}

then all you have to do is declare the radio buttons in the xaml:

RadioButton
Margin="20,20,0,0"
Content="Simple Path"
IsChecked="{Binding Mkft, ElementName=Utils, ConverterParameter=Simple, Converter= {StaticResource enumToBool}, Mode=TwoWay}"
Checked="isClicked"
VerticalAlignment="Top"
HorizontalAlignment="Left"
Width="80"
Height="24" />

This is just one of the three radio buttons, but you will notice that there is no group involved, and you do not need to name them.

The code for isClicked is:

private void isClicked(object sender, RoutedEventArgs e) //get the radiobutton that was pushed
{

textBox2.Text = ((int)Mkft).ToString(); //display the radio button name

Properties.Settings.Default.KmlFileType = (int)Mkft; //save the radio button selection
}

If you want to have one of the buttons pushed, based on user settings, do this in your initialization:

Mkft = (KmlFileTypes)Properties.Settings.Default.KmlFileType;


This couldn't be easier, and it just works!

No comments: