我有一个性别属性:
public string Gender
{
get { return _gender; }
set
{
_gender = value;
OnPropertyChanged();
}
}
还有两个单选按钮来选择两种可用的性别:
<RadioButton GroupName="Group1" Content="Male"/>
<RadioButton GroupName="Group1" Content="Female"/>
我想要做的是将性别字符串设置为男性或女性,具体取决于哪个单选按钮是纯粹从数据投标中选择的,没有后面的代码,如果可以的话,有人可以解释一下吗?我已经为文本框做了这个我只是不确定如何处理单选按钮
一个简单的解决方案是使用 aRadioButton.Command
和RadioButton.CommandParameter
. Binding
或者,使用 a或MultiBinding
与 a 一起使用,但开销稍大IValueConverter
。
此外,您不应该处理纯字符串。更好地定义一个enum
例如Gender
:
主窗口.xaml
<StackPanel>
<RadioButton Command="{Binding SetGenderCommand}"
CommandParameter="{x:Static local:Gender.Male}" />
<RadioButton Command="{Binding SetGenderCommand}"
CommandParameter="{x:Static local:Gender.Female}" />
</StackPanel>
主视图模型.cs
class MainViewModel : INotifyPropertyChanged
{
// Raises PropertyChanged
public Gender Gender { get; set; }
public ICommand SetGenderCommand => new RoutedCommand(ExecuteSetGenderCommand);
private void ExecuteSetGenderCommand(object commandParameter)
=> this.Gender = (Gender)commandParameter;
}
性别.cs
public enum Gender
{
Default = 0,
Female,
Male
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句