如何根据radiobutton的内容设置一些文本?

时间:2022-06-19 22:24:05

I have a fairly basic C#/WPF question. I have a listbox that I can add radio buttons into. I set the listbox selection mode to 'single' so I can only select one at a time. What I want to do is based on what button is selected set some text based on the radio button content.

我有一个相当基本的C#/ WPF问题。我有一个列表框,我可以添加单选按钮。我将列表框选择模式设置为“单个”,因此我一次只能选择一个。我想要做的是根据选择的按钮设置一些基于单选按钮内容的文本。

My code snippet looks like this:

我的代码片段如下所示:

private void Btn_Hello(object sender, RoutedEventArgs e)     
{          
    RadioButton rb = selection.SelectedItem as RadioButton;      
    Hello_box.Text = "hello" + rb.Content;  
}

When I run my code however the selection.selecteditem is null. What do I need to do to fix this?

当我运行我的代码时,selection.selecteditem为null。我需要做些什么来解决这个问题?

1 个解决方案

#1


0  

  private void Btn_Hello(object sender, RoutedEventArgs e)
  {
      RadioButton rb = selection.Items.OfType<RadioButton>().FirstOrDefault(o => o.IsChecked==true);
      if(rb!=null)
          Hello_box.Text = "hello" + rb.Content.ToString();
  }

I think this should help if I understood your question correctly.

我认为如果我正确理解你的问题,这应该会有所帮助。

#1


0  

  private void Btn_Hello(object sender, RoutedEventArgs e)
  {
      RadioButton rb = selection.Items.OfType<RadioButton>().FirstOrDefault(o => o.IsChecked==true);
      if(rb!=null)
          Hello_box.Text = "hello" + rb.Content.ToString();
  }

I think this should help if I understood your question correctly.

我认为如果我正确理解你的问题,这应该会有所帮助。