Jasper Manickaraj
Jasper Manickaraj

Reputation: 837

How to achieve multiple Radiobutton databinding in silverlight mvvm?

I have a question about my Silverlight5 and MVVM pattern ..

In my usercontrol window I have 2 radiobutton controls and I have grouped together the radiobutton controls using GroupName="sex".

Syntax is:

<RadioButton IsChecked="{Binding EntityValue,Mode=TwoWay}" Content="Male"
             GroupName="Sex"
             Visibility="{Binding DataTypeID, Converter={StaticResource radioconverter}}"/>

<RadioButton IsChecked="{Binding EntityValue,Mode=TwoWay}" Content="Female"
             GroupName="Sex"
             Visibility="{Binding DataTypeID, Converter={StaticResource radioconverter}}"/>

I have inserted the checked values to the database using Entity Framework successfully.

For example: my database will be look like this:

CustomerID  | CustomerName | EntityValue |
------------------------------------------
1           | raj          | Male
2           | reena        | Female

Database name is: CDetails

If I have select the customerID=1 means the value Male to be bound to my radioButton1

and

if I have select the customerID=2 means the value Female to be bound to my radioButton2

How is it possible?

Upvotes: 0

Views: 1082

Answers (1)

ChrisF
ChrisF

Reputation: 137148

You need to write a converter to change the EntityValue to a boolean and pass a parameter for the value for which you want it to return true:

<RadioButton IsChecked="{Binding EntityValue, Mode=TwoWay,
                         Converter={StaticResource MyConverter},
                         ConverterParameter=Male}"
             Content="Male"/>

<RadioButton IsChecked="{Binding EntityValue, Mode=TwoWay,
                         Converter={StaticResource MyConverter},
                         ConverterParameter=Female}"
             Content="Female"/>

Then the converter (assuming that your male/female is a string - replace the cast if not):

public class MyConverter: IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        string input = (string)value;
        string test = (string)parameter;
        return input == test;
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        if (value == null || !(value is bool))
        {
            return string.Empty;
        }
        if (parameter == null || !(parameter is string))
        {
            return string.Empty;
        }
        if ((bool)value)
        {
            return parameter.ToString();
        }
        else
        {
            return string.Empty;
        }
    }
}    

Upvotes: 1

Related Questions