4
<GroupBox x:Name="groupBox" Header="Operating System" HorizontalAlignment="Left" Margin="10,10,0,0" VerticalAlignment="Top" Height="74" Width="280">
        <StackPanel>
            <RadioButton GroupName="Os" Content="Windows 7 (64-bit)" IsChecked="True"/>
            <RadioButton GroupName="Os" Content="Windows 7 (32-bit)" />
        </StackPanel>
    </GroupBox>

I have several radio button groups in my application

How can I access which one has been checked in the Code-Behind using C#?

Is it absolutely necessary to use x:Name= on each RadioButton or is there a better way?

Code samples always appreciated

software is fun
  • 7,286
  • 18
  • 71
  • 129

1 Answers1

5

Yes! There is a better way, its called binding. Outside of binding, you are pretty much stuck (I can imagine handling all the checked events separately, and assigning to an enum, but is that really better?)

For radio buttons, you would typically use an enum to represent all the possible values:

public enum OsTypes
{
    Windows7_32,
    Windows7_64
}

And then bind each of your radio buttons to a global "selected" property on your VM. You need a ValueEqualsConverter for this:

    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        return value.Equals(parameter);
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        return ((bool)value) ? parameter : Binding.DoNothing;
    }

And then your radio buttons look like:

<RadioButton Content="Windows 7 32-bit"
             IsChecked= "{Binding CurrentOs, 
                         Converter={StaticResource ValueEqualsConverter},
                         ConverterParameter={x:Static local:OsTypes.Windows7_32}}"

Of course, you have a property in your VM:

public OsTypes CurrentOs {get; set;}

No x:Name, complicated switch statements, or anything else. Nice, clean, and well designed. MVVM works with WPF, use it!

Community
  • 1
  • 1
BradleyDotNET
  • 60,462
  • 10
  • 96
  • 117
  • do I need a different class to manage the radio button? I am very new to MVVM – software is fun May 21 '15 at 19:05
  • @softwareisfun I'm not sure what you mean, but I don't think so. You need a data context (view model) which is the only piece I didn't provide the full code for. If you are having basic issues with MVVM, feel free to join me in the WPF chat room http://chat.stackoverflow.com/rooms/18165/wpf – BradleyDotNET May 21 '15 at 19:10
  • I would just have a bool for each radio button and skip a converter requirement, but I can see how using Enum's is nice – Julien May 21 '15 at 19:22
  • @Julien When it's a true *radio button* (only one selected at a time), the Enum model is *far* more convenient in my opinion. – BradleyDotNET May 21 '15 at 20:49