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

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");

#94 – Naming Elements

If you use drag and drop in Visual Studio 2010 to create new elements and include them in the underlying XAML file, each element is automatically given a name:

 <Button Content="Button" Height="23" Name="button1" Width="75" />
 <Button Content="Button" Height="23" Name="button2" Width="75" />

But setting this Name property is optional.  If you remove the Name properties, the elements will still get created and displayed properly.

Naming elements in XAML is required when you want to reference those elements in your code-behind.  For example, with the named buttons above, we can then write the following C# code:

 button1.Content = "Button 1";
 button2.Content = "This is button 2";

The name is used in code as a reference to the corresponding object created by the XAML parser.