#95 – x:Name vs. Name

You’ll typically see a Name property on XAML elements.  This property can be used in your code-behind, as a reference to the object being created.

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

But you might also see x:Name being used (attribute syntax) in XAML.

 <Viewport3D Name="viewport1">
     <ModelVisual3D x:Name="visual1">
     </ModelVisual3D>
 </Viewport3D>

The Name property can be used with elements that inherit a Name property from their base class (e.g. FrameworkElement).  But for classes that don’t define a Name property or inherit from a class that does, you must use the x:Name property if you want to reference the object from your code-behind.

In general, Name and x:Name are interchangeable.  The former is an actual property on the class and the latter is a directive that comes from the default x: namespace and is used by the XAML parser.

About these ads

About Sean
Software developer in the Twin Cities area, passionate about .NET technologies. Equally passionate about my own personal projects related to family history and preservation of family stories and photos.

One Response to #95 – x:Name vs. Name

  1. Pingback: Tweets that mention #95 – x:Name vs. Name « 2,000 Things You Should Know About WPF -- Topsy.com

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 374 other followers

%d bloggers like this: