#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");
        }
Advertisements