4

I noticed that when naming elements in xaml that we have two options when naming elements.

<Textbox Name="MyTextBox" />

or

<Textbox x:Name="MyOtherTextBox" />

I have seen both used in various examples and would like to know which is best so I can use it in my application. What is the difference between the two?

Edward
  • 7,346
  • 8
  • 62
  • 123

3 Answers3

6

When an element like TextBox has a Name property then there is no difference between using Name or x:Name.

However not all classes that can appear in Xaml have a Name property so trying to use Name on such an element will result in an error. You can use x:Name though. When such an element has an x:Name it can usually be found with the FindName method of a containing FrameworkElement.

See also:- Is there any difference in x:name and name for controls in xaml file?

Community
  • 1
  • 1
AnthonyWJones
  • 187,081
  • 35
  • 232
  • 306
1

You could say that it's a naming convention to ensure consistancy, but also it allows easy differentiation from XML attributes in that you know that the item in question is declared and instantiated or used in some code behind file.

Have a look here for Microsofts take on it (WPF based background) and here for the Silverlight answer.

ChrisBD
  • 9,104
  • 3
  • 22
  • 35
1

It refers to the namespace. In the snippet below, it refers to "xmlns:x". "x:Name" and "Name" is the same.

<UserControl
    x:Class="MyNamespace.MyClass"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    ...>
Peet Brits
  • 2,911
  • 1
  • 31
  • 47