WPF MVVM - 如何将单选按钮绑定到 属性

WPF MVVM - How do I bind a radio button to a property

我有性别属性:

public string Gender
{
    get { return _gender; }
    set
    {
        _gender = value;
        OnPropertyChanged();
    }
}

以及 select 两个可用性别的两个单选按钮:

 <RadioButton  GroupName="Group1" Content="Male"/>
 <RadioButton  GroupName="Group1" Content="Female"/>

我想做的是将性别字符串设置为男性或女性,具体取决于哪个单选按钮 select 纯粹从没有代码隐藏的数据出价中编辑,如果可以的话,有人可以解释一下吗?我已经为文本框做了这个我只是不确定如何处理单选按钮

一个简单的解决方案是使用 RadioButton.CommandRadioButton.CommandParameter。或者,但开销略大,使用 BindingMultiBindingIValueConverter.

此外,您不应处理纯字符串。最好定义一个 enum 例如Gender:

MainWindow.xaml

<StackPanel>
  <RadioButton Command="{Binding SetGenderCommand}"
               CommandParameter="{x:Static local:Gender.Male}" />
  <RadioButton Command="{Binding SetGenderCommand}"
               CommandParameter="{x:Static local:Gender.Female}" />
</StackPanel>

MainViewModel.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;
}

Gender.cs

public enum Gender
{
  Default = 0,
  Female,
  Male
}