Determining checked Radiobutton from groupbox in WPF following MVVM

Xtrem picture Xtrem · Sep 4, 2013 · Viewed 38.9k times · Source

I have a groupbox with some radiobuttons. How do I get to know which one which is checked? I am using WPF and following MVVM.

<GroupBox Name="grpbx_pagerange" Header="Print Range">
    <Grid >
        <RadioButton Name="radbtn_all" Content="All Pages" GroupName="radios_page_range" IsChecked="True"  />
        <RadioButton x:Name="radbtn_curr" Content="Current Page" GroupName="radios_page_range"  />
        <RadioButton Name="radbtn_pages" Content="Page Range" GroupName="radios_page_range" />

        ....

</GroupBox>

Now, one way I could figure out was to bind each RadioButton's IsChecked Property to some property in ViewModel and then do if..else sort of logic in my ViewModel to figure out the selected radiobutton.

But Is there any other elegant way?

Answer

Nitin picture Nitin · Sep 4, 2013

you can bind RadioButton.Command of Radiobuttons to a command of your ViewModel and send a unique CommandParameter to identify which button has called the command in commandhandler.

<RadioButton Command="{Binding MyCommand}" CommandParameter="Radio1"/>
<RadioButton Command="{Binding MyCommand}" CommandParameter="Radio2"/>
<RadioButton Command="{Binding MyCommand}" CommandParameter="Radio3"/>

in command handler check for parameter to identify the radiobutton.

Thanks