简体   繁体   English

如何从已定义的单选按钮组中找到选定的单选按钮

[英]How can I find selected radiobutton from defined group of radiobutton

I hv taken 4 radiobuttons and defined one group for all. 我用了4个单选按钮,并为所有按钮定义了一组。 And I want to find text of selected radiobutton in that group. 我想在该组中查找所选单选按钮的文本。 How to code for this. 如何为此编写代码。 thanks 谢谢

By modifying a bit This post you will get what you want 通过修改了一下这个帖子,你会得到你想要的

As that post says, add this class to your project 如该帖子所述,将此类添加到您的项目中

public static class VisualTreeEnumeration 
{ 
   public static IEnumerable<DependencyObject> Descendents(this DependencyObject root) 
   { 
     int count = VisualTreeHelper.GetChildrenCount(root); 
     for (int i=0; i < count; i++) 
     { 
       var child = VisualTreeHelper.GetChild(root, i); 
       yield return child; 
       foreach (var descendent in Descendents(child)) 
         yield return descendent; 
     } 
   } 
} 

And this will give you result you want 这将给您想要的结果

List<RadioButton> group = this.Descendents()
                               .OfType<RadioButton>()
                               .Where(r => r.GroupName == "aaa" && r.IsChecked == true)
                               .ToList();

From MSDN's RadioButton Class : 从MSDN的RadioButton类

The following example shows two panels that contain three radio buttons each. 以下示例显示了两个面板,每个面板包含三个单选按钮。 One radio button from each panel are grouped together. 每个面板中的一个单选按钮组合在一起。 The remaining two radio buttons on each panel are not grouped explicitly, which means they are grouped together since they share the same parent control. 每个面板上其余的两个单选按钮未明确分组,这意味着它们被分组在一起,因为它们共享相同的父控件。 When you run this sample and select a radio button, a TextBlock displays the name of the group, or "grouped to panel" for a radio button without an explicit group name, and the name of the radio button. 当您运行此示例并选择单选按钮时,TextBlock将显示组的名称,或者不带显式组名的单选按钮“分组到面板”和单选按钮的名称。

XAML XAML

<TextBlock Text="First Group:"  Margin="5" />
<RadioButton x:Name="TopButton" Margin="5" Checked="HandleCheck"
     GroupName="First Group" Content="First Choice" />
<RadioButton x:Name="MiddleButton" Margin="5" Checked="HandleCheck"
     GroupName="First Group" Content="Second Choice" />
<TextBlock Text="Ungrouped:" Margin="5" />
<RadioButton x:Name="LowerButton" Margin="5" Checked="HandleCheck"
    Content="Third Choice" />
<TextBlock x:Name="choiceTextBlock" Margin="5" />

Code Behind 背后的代码

private void HandleCheck(object sender, RoutedEventArgs e)
{
    RadioButton rb = sender as RadioButton;
    choiceTextBlock.Text = "You chose: " + rb.GroupName + ": " + rb.Name;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM