Wednesday 22 August 2012

Gender Selection in RadioBox Control with IValueConverter in WPF

Binding Gender in WPF Radiobutton Control


This is one of my interesting post , when answering to one of the Code project question I did this sample WPF application with Data grid and Radio box control to select the gender of the employee and the same I would like to share in the blog.

The question is here to select an employee from the Data grid and display the details in  Text box's and for gender with Radio button.Here the major part is to concentrate on the gender field.The below image shows the output.



With some of the Google leanings came up with a solution to have an enumeration value  for the gender field and using the IValueConverter interface. Use a ValueConverter combined with ConverterParameter to bind the enumeration to the boolean IsChecked of the radio button control.


The below is the code sample's:

XAML Code:



<Window x:Class="SampleWPFApp.GridWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:Converters="clr-namespace:SampleWPFApp"
        Title="GridWindow" Height="300" Width="300">
    <Window.Resources>       
        <Converters:EnumBooleanConverter x:Key="EnumGender"/>
    </Window.Resources>
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="60"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>
        <Grid DataContext="{Binding ElementName=PersonDatagrid,Path=SelectedItem}">
            <Grid.RowDefinitions>
                <RowDefinition Height="30"></RowDefinition>
                <RowDefinition Height="30"></RowDefinition>                
            </Grid.RowDefinitions>

            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="100"/>
                <ColumnDefinition Width="120"/>
                <ColumnDefinition Width="*"/>
            </Grid.ColumnDefinitions>
            
            <TextBlock Name="Name" Grid.Row="0" Grid.Column="0" Text="Name" HorizontalAlignment="Center" VerticalAlignment="Center"/>
            <TextBox Name="txtName" Grid.Row="0" Grid.Column="1" Height="20" Text="{Binding Name}"/>

            <TextBlock Name="txtgender" Grid.Row="1" Grid.Column="0" Text="Gender" HorizontalAlignment="Center" VerticalAlignment="Center"/>
            <RadioButton GroupName="male" Content="Male" Height="16" Margin="1,5,0,0" Name="MaleRadioButton" VerticalAlignment="Top"  Grid.Column="1" HorizontalAlignment="Left" Width="42" Grid.Row="1" 
                         IsChecked="{Binding Converter={StaticResource EnumGender},Path=Gender,Mode=TwoWay,ConverterParameter=Male}"/>
            <RadioButton GroupName="female" Content="Female" Height="16" HorizontalAlignment="Left" Margin="56,5,0,0" Name="FemaleRadioButton" VerticalAlignment="Top" Grid.Column="1" Grid.Row="1" 
                         IsChecked="{Binding Converter={StaticResource EnumGender},Path=Gender,Mode=TwoWay,ConverterParameter=Female}"/>
        </Grid>

        <DataGrid AutoGenerateColumns="False"  Height="200" HorizontalAlignment="Left" Grid.Row="1" Margin="0,12,0,0" Name="PersonDatagrid" VerticalAlignment="Top">
            <DataGrid.Columns>
                <DataGridTextColumn Header="Name" Width="100" Binding="{Binding Name}"/>
                <DataGridTextColumn Header="Gender" Width="150" Binding="{Binding Gender}"/>               
            </DataGrid.Columns>
        </DataGrid>

    </Grid>
</Window>

Codebehind code for the XAML page:


namespace SampleWPFApp
{
    /// <summary>
    /// Interaction logic for GridWindow.xaml
    /// </summary>
    public partial class GridWindow : Window
    {
        public GridWindow()
        {
            InitializeComponent();
            PersonDatagrid.ItemsSource = new List<PersonalInfo> { 
                new PersonalInfo { Gender =  Genders.Female , Name = "Mariya"},
                new PersonalInfo { Gender = Genders.Male , Name = "Martin"},
                new PersonalInfo { Gender =  Genders.Female , Name = "Jermila"},
                new PersonalInfo { Gender = Genders.Male , Name = "Chand"}};
        }
    }

    public class PersonalInfo
    {
        public string Name { get; set; }
        public Genders Gender { get; set; }
    }

    public enum Genders
    {
        Male = 1,
        Female
    }
}


Converter code for the control:



public class EnumBooleanConverter : IValueConverter
    {
        #region IValueConverter Members

        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            var ParameterString = parameter as string;
            if (ParameterString == null)
                return DependencyProperty.UnsetValue;

            if (Enum.IsDefined(value.GetType(), value) == false)
                return DependencyProperty.UnsetValue;

            object paramvalue = Enum.Parse(value.GetType(), ParameterString);
            return paramvalue.Equals(value);
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            var ParameterString = parameter as string;
            if (ParameterString == null)
                return DependencyProperty.UnsetValue;

            return Enum.Parse(targetType, ParameterString);
        }

        #endregion
    }




Hope this blog post will be useful.

Thanks & Regards
Prabhakaran Soundarapandian

2 comments: