如何在Silverlight中为组单选按钮设置数据绑定?

Ken*_*hou 8 c# data-binding silverlight xaml silverlight-5.0

Sliverlight提供了带有GroupName的单选按钮,可以将radiobutton与多个选项中的一个选项组合在一起.就像是:

<RadioButton GroupName="Option" Content="Option 1"></RadioButton>
<RadioButton GroupName="Option" Content="Option 2"></RadioButton>
<RadioButton GroupName="Option" Content="Option 3"></RadioButton>
Run Code Online (Sandbox Code Playgroud)

然后在VM中,我只有一个属性用于此选项,比如它是MyChoice

public int MyChoice {get; set;}
Run Code Online (Sandbox Code Playgroud)

那么如何在UI和VM之间为这种情况设置数据绑定?

小智 14

使用转换器将bools转换为int:

在Xaml上,asssuming选项映射到MyChoice属性上的1,2,3:

    <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}"/>
Run Code Online (Sandbox Code Playgroud)

在转换器中,注意到我没有添加任何强制转换保护:

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

您最好在ViewModel中实现INotifyPropertyChanged.