The RadioButton class represents a Button that can be selected, but not cleared, by a user. You can set the IsChecked property of a RadioButton by clicking it, but it can only be cleared programmatically. This topic provides examples of how to create a RadioButton control using Extensible Application Markup Language (XAML) and to set event handlers on the control using C#.
This topic contains the following sections.
- RadioButton Control
- Creating RadioButtons
- Creating RadioButton Groups
- Creating RadioButton Groups Using GroupName
- Related Topics
The RadioButton is a control that is usually used as an item in a group of RadioButton controls however, it is possible to create a single RadioButton. A RadioButton control is a ContentControl, which means that it can contain content such as text, images, or panels. RadioButton controls inherit from the ToggleButton class, which in turn inherits from ButtonBase. Because RadioButton controls inherit from ToggleButton, they enable a user to change selections. Unlike a CheckBox, however, the user cannot clear the selected RadioButton by clicking it again. If the RadioButton is part of a group of RadioButton controls, the group contains functionality to manage toggling selections. The following graphic shows an example of a RadioButton control.
The following example shows how to create a single RadioButton with XAML.
<RadioButton Name="rb" FontSize="12" Click="WriteText">Click the radio button. </RadioButton>
After creating the RadioButton, you can add an event handler to handle Click events. Event handlers must be written in a procedural programming language, such as C# or Microsoft Visual Basic. The following event handlers demonstrate this.
Creating RadioButton Groups
When RadioButton elements are grouped, the buttons are mutually exclusive. A user can select only one item at a time within a RadioButton group. Unlike a CheckBox, when a RadioButton is selected it cannot be cleared by clicking it. The application programmatically clears a selected item when the user selects a new item. Whether a RadioButton is selected is determined by the state of its IsChecked property. You can group RadioButton controls by placing them inside a parent or by giving them a group name. The following code sample groups three RadioButton controls inside a StackPanel parent.
Creating RadioButton Groups Using GroupName
You can group RadioButton elements by using the GroupName property. The following code sample creates two separate RadioButton groups: colorgrp and numgrp.
<StackPanel> <RadioButton GroupName="colorgrp">Red</RadioButton> <RadioButton GroupName="colorgrp">Blue</RadioButton> <RadioButton GroupName="numgrp">1</RadioButton> <RadioButton GroupName="numgrp">2</RadioButton> </StackPanel>
For the complete sample see RadioButton Sample.