#299 – Controls Do Not Need a Name

In WPF, giving a control a name is optional.  You name a control a name using the Name attribute.  (You can also use the x:Name attribute to name XAML elements that do not derive from FrameworkElement).

<Button Name="btnSave" Content="Save" Height="25" Width="80" Click="Save_Click"/>

You should give a control a name only if you need to access the control from your code-behind.  When a control has a name, you can use that name to interact with the control from the code-behind.

double buttonArea = btnSave.Height * btnSave.Width;
btnSave.Focus();

Notice that you don’t need to name a control in order to attach an event handler to it. You only need to define the name of the handler in the XAML.

		<Button Content="Save" Height="25" Width="80" Click="Save_Click"/>

The code-behind then defines the handler using the same name.

        private void Save_Click(object sender, RoutedEventArgs e)
        {
            MessageBox.Show("You clicked on the Save button");
        }
Advertisement

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

One Response to #299 – Controls Do Not Need a Name

  1. Pingback: #499 – Interacting with the Control That Initiated an Event « 2,000 Things You Should Know About WPF

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: