How can I get a link to a group of hams and find the selected one?

Using the following XAML, how can I get a link to the selected radio object in the button event handler?

<Window x:Class="WpfApplication1.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="MainWindow" Height="350" Width="525" x:Name="myWindow"> <Grid> <StackPanel> <RadioButton Content="A" GroupName="myGroup"></RadioButton> <RadioButton Content="B" GroupName="myGroup"></RadioButton> <RadioButton Content="C" GroupName="myGroup"></RadioButton> </StackPanel> <Button Click="Button_Click" Height="100" Width="100"></Button> </Grid> </Window> 
+4
source share
2 answers

The easiest way is to give each RadioButton a name and check its IsChecked property.

 <RadioButton x:Name="RadioButtonA" Content="A" GroupName="myGroup"></RadioButton> <RadioButton x:Name="RadioButtonB" Content="B" GroupName="myGroup"></RadioButton> <RadioButton x:Name="RadioButtonC" Content="C" GroupName="myGroup"></RadioButton> if (RadioButtonA.IsChecked) { ... } else if (RadioButtonB.IsChecked) { ... } else if (RadioButtonC.IsChecked) { ... } 

But using Linq and a logical tree, you can make this a little less verbose:

 myWindow.FindDescendants<CheckBox>(e => e.IsChecked).FirstOrDefault(); 

Where FindDescendants is a reusable method:

  public static IEnumerable<T> FindDescendants<T>(this DependencyObject parent, Func<T, bool> predicate, bool deepSearch = false) where T : DependencyObject { var children = LogicalTreeHelper.GetChildren(parent).OfType<DependencyObject>().ToList(); foreach (var child in children) { var typedChild = child as T; if ((typedChild != null) && (predicate == null || predicate.Invoke(typedChild))) { yield return typedChild; if (deepSearch) foreach (var foundDescendant in FindDescendants(child, predicate, true)) yield return foundDescendant; } else { foreach (var foundDescendant in FindDescendants(child, predicate, deepSearch)) yield return foundDescendant; } } yield break; } 
+4
source

You can use a ListBox as shown in this answer , this works by templating the RadioButtons elements bound to the IsSelected ListBoxItem and then binding the ListBox.SelectedItem to the property.

+1
source

Source: https://habr.com/ru/post/1397821/


All Articles