如何获取wpf中选中的单选按钮的值

Dor*_*Z11 5 c# wpf radio-button gridpanel

RadioButtons在网格面板中有四个,但是当我这样做时:

<GroupBox x:Name="radioButtons">
    <RadioButton Content="1" Height="16" HorizontalAlignment="Left" Margin="10,45,0,0" Name="status1" VerticalAlignment="Top" />
    <RadioButton Content="2" Height="16" HorizontalAlignment="Left" Margin="10,67,0,0" Name="status2" VerticalAlignment="Top" />
    <RadioButton Content="3" Height="16" HorizontalAlignment="Left" Margin="10,89,0,0" Name="status3" VerticalAlignment="Top" />
    <RadioButton Content="4" Height="16" HorizontalAlignment="Left" Margin="10,111,0,0" Name="status4" VerticalAlignment="Top" />
</GroupBox>
Run Code Online (Sandbox Code Playgroud)

它说:

错误 1 ​​对象“GroupBox”已经有一个子项,无法添加“RadioButton”。“GroupBox”只能接受一个孩子。

最后三个RadioButtons说:

属性“内容”设置了不止一次。

我的GroupBox怎么了?此外,在我的代码中,我想访问RadioButton被检查的(最好是int)。我该怎么做呢?我试着在谷歌上搜索,发现了很多结果,但我一个都看不懂。

Viv*_*Viv 5

GroupBox只能容纳 1 个项目,因此关于尝试多次设置Content属性的错误GroupBox

因此,将其设为 Layout 项,然后将RadioButtons 放入其中。现在,您设置了Content一次,即StackPanel,并且该 Layout 项可以容纳许多子项 -> RadioButtons。

<GroupBox x:Name="radioButtons">
  <StackPanel>
    <RadioButton Name="status1"
                  Height="16"
                  Margin="10,45,0,0"
                  HorizontalAlignment="Left"
                  VerticalAlignment="Top"
                  Content="1" />
    <RadioButton Name="status2"
                  Height="16"
                  Margin="10,67,0,0"
                  HorizontalAlignment="Left"
                  VerticalAlignment="Top"
                  Content="2" />
    <RadioButton Name="status3"
                  Height="16"
                  Margin="10,89,0,0"
                  HorizontalAlignment="Left"
                  VerticalAlignment="Top"
                  Content="3" />
    <RadioButton Name="status4"
                  Height="16"
                  Margin="10,111,0,0"
                  HorizontalAlignment="Left"
                  VerticalAlignment="Top"
                  Content="4" />
  </StackPanel>
</GroupBox>
Run Code Online (Sandbox Code Playgroud)

至于你的第二个问题,Christian Mosers WPF Tutorial.net有一个不错的样本。如果你不明白,你也许应该先看看主题BindingConverter

RadioButton以非 MVVM 方式通知检查的一种非常粗略的方式:

private void RadioButtonChecked(object sender, RoutedEventArgs e) {
  var radioButton = sender as RadioButton;
  if (radioButton == null)
    return;
  int intIndex = Convert.ToInt32(radioButton.Content.ToString());
  MessageBox.Show(intIndex.ToString(CultureInfo.InvariantCulture));
}
Run Code Online (Sandbox Code Playgroud)

然后,在RadioButtonxaml中的每个s 中,添加Checked="RadioButtonChecked".