Blog
Radio Button Control - Visual C#
Excerpt by Robert Green and Ken Getz | January 03, 2014
The RadioButton control works much like the CheckBox control-it provides the same properties, and the same events. The big difference between the RadioButton and CheckBox controls is that RadioButton controls are grouped by their container. Within a single container, you can generally only select one RadioButton control. If you place multiple RadioButton controls into multiple containers, you can select one RadioButton control from each container. You can override this behavior using the GroupName property of the control. You can set this string value to create more than one group per container, or to create a single group that spans multiple containers. To demonstrate this behavior, select the RadioButton tab in the sample application, shown in Figure 1.
TIP: There's no need to specify a GroupName property for a RadioButton control unless you want to override the default behavior.
Figure 1. RadioButton controls normally allow you to select only one per container; override the behavior with the GroupName property.
The markup for the sample page looks like the following:
If you try out the demonstration, you'll see that you can only select a RadioButton control from the group named Group 1, because they're all in the same container. You can select only a single item from the group named Group 2, again, because they're in the same container. You can also select one item from the group named Group 3, because these items have their GroupName property set to the same text (the text is arbitrary, and it's set to Group3 in the example).
Because these controls share the same group name, and because they have a group name set, you can select multiple RadioButton controls within a single container. In contrast, the right-hand Border control contains multiple CheckBox controls. Nothing keeps you from selecting as many CheckBox controls as you like. That's the point: When you use RadioButton controls, you intend for users to select only one per group. When you use CheckBox controls, you intend users to select multiple items.
NOTE This sample uses a StackPanel control as the container for the groups of RadioButton controls. You may also want to investigate the GroupBox control, which not only groups the controls but also adds a caption describing the group. The GroupBox control is, effectively a simple container with a caption added.
This post is an excerpt from the online courseware Windows Presentation Foundation Using Visual C# 2010 course written by expert Ken Getz and Robert Green.
Robert Green
Ken Getz
This course excerpt was originally posted January 03, 2014 from the online courseware Windows Presentation Foundation Using Visual C# 2010 by Robert Green and Ken Getz