Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set up data binding for group radio button in Silverlight?

Sliverlight provides radio button with GroupName to group radiobutton together with only one option from mutiple choice. It's like:

<RadioButton GroupName="Option" Content="Option 1"></RadioButton>
<RadioButton GroupName="Option" Content="Option 2"></RadioButton>
<RadioButton GroupName="Option" Content="Option 3"></RadioButton>

then in VM, I have only one property for this option,say it's MyChoice

public int MyChoice {get; set;}

then how to setup data binding for this case between UI and VM?

like image 962
KentZhou Avatar asked Aug 01 '13 15:08

KentZhou


1 Answers

Used a converter to convert bools to an int:

On Xaml, asssuming options map to 1,2,3 on your MyChoice property:

    <RadioButton GroupName="Option" Content="Option 1"
                 IsChecked="{Binding Path=MyChoice, Converter={StaticResource RadioButtonToIntConverter}, 
        ConverterParameter=1}"/>
    <RadioButton GroupName="Option" Content="Option 2"
                 IsChecked="{Binding Path=MyChoice, Converter={StaticResource RadioButtonToIntConverter}, 
        ConverterParameter=2}"/>
    <RadioButton GroupName="Option" Content="Option 3"
                 IsChecked="{Binding Path=MyChoice, Converter={StaticResource RadioButtonToIntConverter}, 
        ConverterParameter=3}"/>

In the converter, noting that I did not add any cast protection:

public class RadioButtonToIntConverter:IValueConverter 
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        var para = System.Convert.ToInt32(parameter);
        var myChoice = System.Convert.ToInt32(value);
        return para == myChoice;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        var para = System.Convert.ToInt32(parameter);
        var isChecked = System.Convert.ToBoolean(value);
        return isChecked ? para : Binding.DoNothing;
    }
}

Also you'd better to implement INotifyPropertyChanged in you ViewModel.

like image 145
Bill Zhang Avatar answered Sep 27 '22 20:09

Bill Zhang