5

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>
ekad
  • 14,436
  • 26
  • 44
  • 46
HerbalMart
  • 1,669
  • 3
  • 27
  • 50

3 Answers3

7

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;
    }
Ross
  • 4,460
  • 2
  • 32
  • 59
2

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

Community
  • 1
  • 1
H.B.
  • 166,899
  • 29
  • 327
  • 400
1

A little bit less hairy of a way than the accepted answer, if you know your container's ID:

var radioButtons = LogicalTreeHelper.GetChildren(_myStackPanel).OfType<RadioButton>();
var selected = radioButtons.FirstOrDefault(x => (bool)x.IsChecked);
Vulc4n
  • 59
  • 6
Daniel
  • 10,864
  • 22
  • 84
  • 115