开发者

How can I find selected radiobutton from defined group of radiobutton

开发者 https://www.devze.com 2023-02-16 13:04 出处:网络
I hv taken 4 radiobuttons and defined one group for all. And I want to fi开发者_如何转开发nd text of selected radiobutton in that group. How to code for this. thanksBy modifying a bit This post you wi

I hv taken 4 radiobuttons and defined one group for all. And I want to fi开发者_如何转开发nd 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:

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.

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;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消