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