RadioButton Example
This page was last reviewed on Sep 29, 2022.
Dot Net Perls
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.
Shows a radiobutton
Control notes. We use a RadioButton in WPF, handling its Checked event. Please create a WPF application and drag two RadioButton controls to the window.
Checked example. Add the "Checked" attribute to each "RadioButton" element in the XAML. Have Visual Studio create RadioButton_Checked.
Detail 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.
Detail In RadioButton_Checked, we access the RadioButton object that raised the event. We cast the "sender" object to a RadioButton.
Finally We then call ToString on its Content property and change the Window Title.
Shows a radiobutton
<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>
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. 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.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Sep 29, 2022 (edit).
© 2007-2024 Sam Allen.