Name. 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.
Property notes. Name allows controls to interact. The name properties are automatically added in Visual Studio. This property connects markup and code.
Example. 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.
Note We specify the "Name" on the Button (MainButton) and the Name on the CheckBox (MainCheckBox). Sorry for the unimaginative names.
Next We add the Checked and Unchecked event handlers to the 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();
}
}
}
}
Named controls. The MainCheckBox and the MainButton controls are accessed within the CheckBox_Checked event handler. Those names match the Name attributes set in the XAML.
Tip This is the easiest way to get a specific control. No searching or loop-based algorithm is needed.
Detail The Name from the XAML is transformed into a property on the MainWindow class, ready for use.
Summary. 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.
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 28, 2022 (edit).