如何在wpf中获取已检查单选按钮的值

问题描述 投票:2回答:2

我在网格面板中有四个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>

它说:

错误1对象'GroupBox'已经有一个子节点,无法添加'RadioButton'。 'GroupBox'只能接受一个孩子。

最后三个RadioButtons说:

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

我的GroupBox有什么问题?此外,在我的代码中,我想访问被检查的RadioButton(最好是int)。我该怎么做呢?我试图查看谷歌,我发现了很多结果,但我无法理解它们中的任何一个。

c# wpf radio-button gridpanel
2个回答
4
投票

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

因此,将其设为Layout项,然后将RadioButtons放入其中。现在,你设置Content一次,这是StackPanel,而布局项目可以容纳许多孩子 - > 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>

至于你的第二个问题,Christian Mosers WPF Tutorial.net有一个不错的样本。如果您不理解它,您可能应首先查看BindingConverter主题。

以非MVVM方式检查RadioButton的非常粗略的方式:

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));
}

然后,在xaml中的每个RadioButtons中,添加Checked="RadioButtonChecked"


0
投票

如果您需要许多元素或控件,则必须将它们放在布局容器中。

  • StackPanel中
  • DockPanel中
  • WrapPanel
  • 等等.....
© www.soinside.com 2019 - 2024. All rights reserved.