命名元素时 XAML 中 x: 前缀的用途是什么?
我注意到,在 xaml 中命名元素时,我们有两个选项。
<Textbox Name="MyTextBox" />
或者
<Textbox x:Name="MyOtherTextBox" />
我已经看到两者都在各种示例中使用,并且想知道哪一个最好,以便我可以在我的应用程序中使用它。两者有什么区别?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
当像
TextBox
这样的元素具有Name
属性时,使用Name
或x:Name
之间没有区别。但是,并非 Xaml 中出现的所有类都具有
Name
属性,因此尝试在此类元素上使用Name
将导致错误。不过,您可以使用x:Name
。当此类元素具有x:Name
时,通常可以使用包含的FrameworkElement
的FindName
方法找到它。另请参阅:- 是否有xaml 文件中的 x:name 和控件名称有什么区别吗?
When an element like
TextBox
has aName
property then there is no difference between usingName
orx:Name
.However not all classes that can appear in Xaml have a
Name
property so trying to useName
on such an element will result in an error. You can usex:Name
though. When such an element has anx:Name
it can usually be found with theFindName
method of a containingFrameworkElement
.See also:- Is there any difference in x:name and name for controls in xaml file?
您可以说这是一种确保一致性的命名约定,但它也可以轻松区分 XML 属性,因为您知道相关项目是在文件隐藏的某些代码中声明和实例化或使用的。
看看此处 Microsoft 对此的看法(基于 WPF 的背景)并此处银光答案。
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.
它指的是命名空间。在下面的代码片段中,它引用“xmlns:x”。 “x:Name”和“Name”是相同的。
It refers to the namespace. In the snippet below, it refers to "xmlns:x". "x:Name" and "Name" is the same.