从单选按钮 wpf C# 获取输入



瞧,XML 代码


<GroupBox x:Name="radioButtons">
    <StackPanel Orientation="Horizontal">
        <RadioButton Content="Teacher" HorizontalAlignment="Left" Margin="168,171,0,0" VerticalAlignment="Top"/>
        <RadioButton Content="Student" HorizontalAlignment="Left" Margin="20,171,0,0" VerticalAlignment="Top"/>
    </StackPanel>
</GroupBox>

CS 文件代码


private void save_data(object sender, RoutedEventArgs e)
{
    window2 win2 = new window2();
    //var type = sender as RadioButton;
    var type = radioButtons.Content;
    MessageBox.Show(type.ToString());// here when it displays " System.Windows.Controls.StackPanel "
    if (type.ToString().Length <= 0)
        MessageBox.Show("Please select a type.");
    else
        win2.name.Text = type.ToString();
    win2.Show();
    //this.Close();
}

您可以使用私有变量来维护所选单选按钮的内容。将"已检查"事件添加到两个单选按钮,两个单选按钮的同一事件。

    private string radioContent = "";
    private void RadioButton_Checked(object sender, RoutedEventArgs e)
    {
        var radio = (sender as RadioButton);
        radioContent = radio.Content.ToString();
    }
and on the save button click,
  private void save_data(object sender, RoutedEventArgs e)
  {
   window2 win2 = new window2();
   MessageBox.Show(radioContent);// here when it displays " System.Windows.Controls.StackPanel "
  if (radioContent.Length <= 0)
    MessageBox.Show("Please select a type.");
  else
    win2.name.Text = radioContent.ToString();
  win2.Show();
  //this.Close();
   }

最新更新