x:Name 和 Name 引用不同的命名空间。
x:name 是对 Xaml 文件顶部默认定义的 x 命名空间的引用。
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
只是说 Name 使用下面的默认命名空间。
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
x:Name 是说使用具有 x 别名的命名空间。 x 是默认值,大多数人都会保留它,但您可以将其更改为您喜欢的任何内容
xmlns:foo="http://schemas.microsoft.com/winfx/2006/xaml"
所以您的参考将是 foo:name
Define and Use Namespaces in WPF
好的,让我们换一种方式来看待这个问题。假设您将一个按钮拖放到您的 Xaml 页面上。您可以参考这两种方式 x:name 和 name。所有 xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 和
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 是对多个命名空间的引用。由于 xaml 拥有 Control 命名空间(不是 100%)并且 presentation 拥有 FrameworkElement 和 按钮类有一个继承模式:
Button : ButtonBase
ButtonBase : ContentControl, ICommandSource
ContentControl : Control, IAddChild
Control : FrameworkElement
FrameworkElement : UIElement, IFrameworkInputElement,
IInputElement, ISupportInitialize, IHaveResources
正如人们所期望的那样,从 FrameworkElement 继承的任何东西都可以访问其所有公共属性。因此,对于 Button,它从 FrameworkElement 获取其 Name 属性,位于层次结构树的最顶端。 所以您可以说 x:Name 或 Name,它们都会从 FrameworkElement 访问 getter/setter。
MSDN Reference
WPF 定义了 XAML 处理器使用的 CLR 属性,以便将多个 CLR 命名空间映射到单个 XML 命名空间。 XmlnsDefinitionAttribute 属性放置在生成程序集的源代码中的程序集级别。 WPF 程序集源代码使用此属性将各种常用命名空间(例如 System.Windows 和 System.Windows.Controls)映射到 http://schemas.microsoft.com/winfx/2006/xaml/presentation 命名空间。
所以程序集属性看起来像:
PresentationFramework.dll - XmlnsDefinitionAttribute:
[assembly: XmlnsDefinition("http://schemas.microsoft.com/winfx/2006/xaml/presentation", "System.Windows")]
[assembly: XmlnsDefinition("http://schemas.microsoft.com/winfx/2006/xaml/presentation", "System.Windows.Data")]
[assembly: XmlnsDefinition("http://schemas.microsoft.com/winfx/2006/xaml/presentation", "System.Windows.Navigation")]
[assembly: XmlnsDefinition("http://schemas.microsoft.com/winfx/2006/xaml/presentation", "System.Windows.Shapes")]
[assembly: XmlnsDefinition("http://schemas.microsoft.com/winfx/2006/xaml/presentation", "System.Windows.Documents")]
[assembly: XmlnsDefinition("http://schemas.microsoft.com/winfx/2006/xaml/presentation", "System.Windows.Controls")]