Binding Multiple Radio Buttons To a single Enum Property in WPF

I had a property in my View Model, of an Enum type, and wanted to bind multiple radio buttons to this.
Firstly, I wrote a simple Enum to Bool converter, like this. 

public class EnumToBoolConverter : IValueConverter
{
#region IValueConverter Members
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{ if (parameter.Equals(value)) return true;
else
return false; }
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (((bool)value) == true)
{
return parameter;
}
else
{
return DependencyProperty.UnsetValue;
}
}

#endregion
}

//========================================

And my enumeration is like

public enum CompanyTypes
    {
        Type1Comp,
        Type2Comp,
        Type3Comp
    }

Now, in my XAML, I provided the enumeration as the ConverterParameter, of the Converter we wrote earlier, like

<Window x:Class="WpfTestRadioButtons.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:WpfTestRadioButtons"
    Title="Window1" Height="300" Width="300">
    <Window.Resources>
        <local:EnumToBoolConverter x:Key="EBConverter"/>
    </Window.Resources>
    <Grid>
        <StackPanel>
            <RadioButton IsChecked="{Binding Path=Type, 
                Converter={StaticResource EBConverter}, 
                ConverterParameter={x:Static local:CompanyTypes.Type1Comp}}" Content="Type1"/>
            <RadioButton IsChecked="{Binding Path=Type, 
                Converter={StaticResource EBConverter}, 
                ConverterParameter={x:Static local:CompanyTypes.Type2Comp}}" Content="Type2"/>
        </StackPanel>

    </Grid>
</Window>

Now, in the view model, I exposed a property named Type, which is of the CompanyEnum type. Like,

public CompanyTypes Type 
        {
            get
            {
                return _type;
            }
            set
            {
                _type = value;
                if (PropertyChanged != null)
                    PropertyChanged(this, new PropertyChangedEventArgs("Type"));

            }
        }
Advertisements
By Sriramjithendra Posted in WPF

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 )

Google+ photo

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

Connecting to %s