TheDeveloperBlog.com


WPF Name Property: Get Controls

Name. Controls in WPF are accessed by their names. We specify the Name property in the XAML, and then can access the control by that name directly in C# code. This allows controls to interact.

Based on:

.NET 4.5


Example. We create a new WPF project and drag two controls to the Grid: a Button and a CheckBox. We specify the "Name" on the Button (MainButton) and the Name on the CheckBox (MainCheckBox).

Button

Note: Sorry for the unimaginative names. It would be better to use more descriptive names that convey meaning.

Next, we add the Checked and Unchecked event handlers to the CheckBox. We allow Visual Studio to create a new event handler (CheckBox_Checked). And in this event handler, we use the named controls.

CheckBox
Example markup: XAML

<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>

Example code: C#

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. Please notice how 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.

Instead: The Name from the XAML is transformed into a property on the MainWindow class, ready for use.

Property

Summary. The Name property is useful in WPF programs. It allows programmatic access to controls from anywhere in the code. The control properties are automatically added in Visual Studio. This property connects markup and code.