RadioButton groups

One of many problems I was facing while developing software using XAML was how to organize the code if there are many radio buttons which depend on each other.

Radio buttons allow you to force the user to only select one of the possible answers by deselecting everything that was selected before the last click. In order to allow multiple single selections this deselecting would only happen to the radio buttons inside the same controls for example:

<StackPanel>
<RadioButton x:Name="First" Width="100" Height="20"/>
<RadioButton x:Name="Second" Width="100" Height="20"/>
</StackPanel>

Selecting First would automatically deselect Second and vice versa. If they weren’t inside the same control nothing would happen (both radio buttons can be selected at the same time).

 <RadioButton x:Name="First" Width="100" Height="20"/>
 <StackPanel>
 <RadioButton x:Name="Second" Width="100" Height="20"/>
 </StackPanel>

To avoid manipulating with XAML to much you can just use the GroupName attached property to take care of grouping for you. It would look something like this:

<Grid>
<Grid.RowDefinitions>
    <RowDefinition Height="50"/>
<RowDefinition/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>

<TextBlock Grid.Row="0" Grid.Column="0" Text="No Group Name"/>
<RadioButton Width="100" Height="20" GroupName="a" Grid.Row="1"/>
<StackPanel Grid.Row="1">
<RadioButton Width="100" Height="20"/>
</StackPanel>

<TextBlock Grid.Row="0" Grid.Column="1" Text="With Group Name"/>
<RadioButton Width="100" Height="20" GroupName="group" Grid.Row="2" Grid.Column="1"/>
<StackPanel Grid.Row="2"  Grid.Column="1">
<RadioButton Width="100" Height="20"  GroupName="group"/>
</StackPanel>
</Grid>

Most people know about this but I for some reason didn’t know about it until an hour ago so I thought that sharing it might be a good idea.

Until next time, happy coding

Book challenge, week 20

Book challenge, week 19