Controls in WPF are accessed by their Name properties. We specify the Name property in the XAML, and then can access the control by that name directly in C# code.
Name allows controls to interact. The name properties are automatically added in Visual Studio. This property connects markup and code.
We create a new WPF project and drag 2 controls to the Grid
: a Button
and a CheckBox
. We will use the Name attribute to make these 2 controls talk to each other.
Button
(MainButton
) and the Name on the CheckBox
(MainCheckBox
). Sorry for the unimaginative names.CheckBox
. We allow Visual Studio to generate CheckBox_Checked
.<Window x:Class="WpfApplication26.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> <Button Content="Button" HorizontalAlignment="Left" Margin="10,10,0,0" VerticalAlignment="Top" Width="75" Name="MainButton"/> <CheckBox Content="CheckBox" HorizontalAlignment="Left" Margin="10,35,0,0" VerticalAlignment="Top" Checked="CheckBox_Checked" Unchecked="CheckBox_Checked" Name="MainCheckBox"/> </Grid> </Window>using System.Windows; namespace WpfApplication26 { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } private void CheckBox_Checked(object sender, RoutedEventArgs e) { // ... Access MainCheckBox by name. // Use its IsChecked property. bool? state = this.MainCheckBox.IsChecked; if (state.HasValue) { // ... Access MainButton by name. this.MainButton.Content = state.ToString(); } } } }
The MainCheckBox
and the MainButton
controls are accessed within the CheckBox_Checked
event handler. Those names match the Name attributes set in the XAML.
MainWindow
class
, ready for use.The Name property is useful. It allows programmatic access to controls from anywhere in the code. It is often set automatically, but we can adjust it in the XAML.