Home
Search
WPF Name Property: Get ControlsExplore the Name property and see how Name is used within C# code.
dot net perls
Name. Controls in WPF are accessed by their names (and the Name property). 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.
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).
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).
CheckBox
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
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>
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(); } } } }
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.
Home
© 2007-2021 sam allen. see site info on the changelog