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

时间:2015-04-12 05:05:52

标签: c# wpf-controls

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

1 个答案:

答案 0 :(得分:1)

您可以使用私人变量来维护所选单选按钮的内容。 将Checked事件添加到RadioButton,两个单选按钮的相同事件。

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