HomeSearch

WPF RadioButton Example (Checked)

Use the WPF RadioButton control. Handle the RadioButton_Checked event.

RadioButton.

A RadioButton offers an option. It is always visible, and is part of a group of other RadioButtons. One option can be "checked" at a time by the user. We use a RadioButton in WPF, handling its Checked event.

Example.

First, please create a WPF application and drag two RadioButton controls to the window. Next, add the "Checked" attribute to each "RadioButton" element in the XAML. Have Visual Studio create RadioButton_Checked.

Checked: The Checked event is triggered when the user clicks or selects a RadioButton. The "check" is a black circle.

Note: We can have both RadioButton elements point to a single RadioButton_Checked method. Two different methods could instead be used.

In RadioButton_Checked,

we access the RadioButton object that raised the event. We cast the "sender" object to a RadioButton type with the as-cast. We then call ToString on its Content property and change the Window Title.AsProperty
Example markup: XAML <Window x:Class="WpfApplication16.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="MainWindow" Height="350" Width="525"> <Grid> <RadioButton Content="Dogs" Checked="RadioButton_Checked" HorizontalAlignment="Left" Margin="10,10,0,0" VerticalAlignment="Top"/> <RadioButton Content="Cats" Checked="RadioButton_Checked" HorizontalAlignment="Left" Margin="10,30,0,0" VerticalAlignment="Top"/> </Grid> </Window> Example code: C# using System.Windows; using System.Windows.Controls; namespace WpfApplication16 { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } private void RadioButton_Checked(object sender, RoutedEventArgs e) { // ... Get RadioButton reference. var button = sender as RadioButton; // ... Display button content as title. this.Title = button.Content.ToString(); } } }

Discussion.

How can you keep track of which RadioButton is currently checked? One way involves uses a field. Store a field (int, string) on the MainWindow class. And in Checked, assign it to the result of the Content.ToString() method.

Then: You can access this field anywhere (in any method) in your WPF program to determine which RadioButton is checked.

Summary.

A CheckBox control may be checked at the same time as another. But only one RadioButton control can be checked. For this reason, a RadioButton can be used to select an exclusive option, such as a program mode.CheckBox
Home
Dot Net Perls
© 2007-2019 Sam Allen. All rights reserved. Written by Sam Allen, info@dotnetperls.com.