From this https://stackoverflow.com/questions/2284752/mvvm-binding-radio-buttons-to-a-view-model and this https://stackoverflow.com/questions/883246/mvvm-radiobuttons(和其他)关于 Stack Overflow 和互联网上许多其他材料的问题,我了解了如何将单选按钮(选项按钮)与视图模型绑定。
但它们都为单选按钮的每个可能值创建单独的属性。一question https://stackoverflow.com/questions/28571283/radiobuttons-with-behavior-bind-to-single-property与我的要求类似,但接受的答案建议使用ListBox
而不是单选按钮。
例如,要表示人的性别(数据类型Char
, 可能的值'M'
, 'F'
),需要在视图模型中创建三个属性:PersonGender
, IsPersonMale
, IsPersonFemale
.
我只想在一个属性上控制这个PersonGender
。
我可以这样做吗?如果是,怎么办?
你需要一个IValueConverter
.
//define this in the Window's Resources section or something similiarly suitable
<local:GenderConverter x:Key="genderConverterKey" />
<RadioButton Content="M" IsChecked="{Binding Gender, Converter={StaticResource ResourceKey=genderConverterKey}, ConverterParameter=M}" />
<RadioButton Content="F" IsChecked="{Binding Gender, Converter={StaticResource ResourceKey=genderConverterKey}, ConverterParameter=F}" />
转换器
public class GenderConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
return ((string)parameter == (string)value);
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
return (bool)value ? parameter : null;
}
}
Replace null
(in ConvertBack
) with Binding.DoNothing
如果在这种情况下不应应用绑定。
return (bool)value ? parameter : Binding.DoNothing;
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)