簡體   English   中英

如何在WPF中獲取選中的單選按鈕的值

[英]How to get the value of the checked radiobutton in wpf

我在網格面板中有四個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 )。 我該怎么做呢? 我嘗試查看Google,但發現了很多結果,但我聽不懂。

GroupBox只能容納1個項目,因此有關嘗試多次設置GroupBoxContent屬性的錯誤。

因此,將其設置為Layout項,然后將RadioButton放入其中。 現在,您一次設置Content ,即StackPanel ,並且Layout項可以容納許多子項-> RadioButton

<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中的每個RadioButton中,添加Checked="RadioButtonChecked"

如果需要許多元素或控件,則必須將它們放在布局容器中。

  • StackPanel中
  • DockPanel中
  • WrapPanel
  • 等等.....

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM