Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fetching selected radio button in wpf

Tags:

c#

.net

wpf

In WinForms I've used panel to group radio buttons and then this code to fetch selected radio button

var checkedValue = panelMyPanel.Controls.OfType<RadioButton>()
                        .FirstOrDefault(r => r.Checked);

Now I want to translate this to wpf and inside xaml I added radio buttons

 <RadioButton GroupName="myGroup" Name="Option1" Content="option one" IsChecked="True"  Width="40"/>
 <RadioButton GroupName="myGroup" Name="Option2" Content="option two" IsChecked="False" Width="80"/>
 <RadioButton GroupName="myGroup" Name="Option3" Content="option three" IsChecked="False" Width="60"/>

how to know which radio btn is selected in code behind?

like image 654
panjo Avatar asked Dec 30 '13 17:12

panjo


1 Answers

Almost same, suppose these are child of stackPanels, it will be like this:

<StackPanel x:Name="panel">
  <RadioButton/>
  <RadioButton/>
  <RadioButton/>
</StackPanel>

Code:

var checkedValue = panel.Children.OfType<RadioButton>()
                 .FirstOrDefault(r => r.IsChecked.HasValue && r.IsChecked.Value);

Since radio button IsChecked property is nullable bool, so you need to check first HasValue and then Value.

like image 90
Rohit Vats Avatar answered Nov 01 '22 14:11

Rohit Vats