Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get a reference to a group of radiobuttons and find the selected one?

Using the following XAML how can I get a reference to the selected radiobutton in the eventhandler of the Button?

<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>
like image 245
HerbalMart Avatar asked Feb 22 '12 13:02

HerbalMart


1 Answers

The simplest way would be to give each RadioButton a name, and test 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 the Logical Tree you can make it a bit less verbose:

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

Where FindDescendants is a reusable extension 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;
    }
like image 145
Ross Avatar answered Sep 16 '22 23:09

Ross