当我在 XAML 中导入命名空间时会发生什么?

What happens when I import a namespace in XAML?

我有一个软件项目正在 WPF 中与其他几个 "Helper" 程序集一起工作,结构如下:

在 "Controls" 程序集中,我有几个命名空间将相关类型的控件组合在一起。这使得管理哪些代码在这个程序集中的位置变得容易,因为命名空间与文件夹名称相同。

但是,当我在项目的其他部分使用这些控件时,这可能会有点混乱,尤其是当我有时不得不在同一个文件中使用多个名称空间声明来引用 "Controls" 组装。

我一直在想,将我的所有控件放入一个我可以随处使用的更集中的命名空间是否更有意义。这样做的障碍是,每次我使用该名称空间时,它都会引用程序集中的所有控件。但是,它会让我的 XAML 更干净。

那么,当我在 XAML 中导入命名空间引用时,实际发生了什么?它的工作方式与 C# 中的相同吗?如果我有一堆未使用的引用,会发生什么?如果我将所有控件都放在同一个命名空间中,从性能的角度来看是否可以?

或者,我是不是太傻了,问了完全错误的问题?

I have been wondering whether it would make more sense to put all of my controls into a more centralised namespace that I can use everywhere.

真的没有必要这么做。

The barrier against doing this is that every time I use that namespace it would reference all of the controls in the assembly. [...] So, what actually happens when I import a namespace reference in XAML? [...] What happens if I have a bunch of unused references sitting around?

没什么大不了的。 XAML 命名空间只是在编译时解析对象引用的机制。任何未使用的引用最终都会被编译器忽略。它对性能没有影响。

And would it be okay from a performance perspective if I put all of my controls into the same namespace?

性能不会受到任何影响,但我建议保留您现有的文件和文件夹结构。

您可以使用 XmlnsDefinitionAttribute 将来自不同 C# 命名空间的控件放入相同的 logical XAML 命名空间。这个属性放在AssemblyInfo.cs文件中,像这样:

[assembly: XmlnsDefinition("http://mycompany.com/controls", "MyCompany.Controls.Core")]
[assembly: XmlnsDefinition("http://mycompany.com/controls", "MyCompany.Controls.Primitives")]

在引用 this 程序集的程序集中,您可以执行如下操作:

...
xmlns:mycontrols="http://mycompany.com/controls"
...
<mycontrols:Foo ... />
<mycontrols:Bar ... />

因此 Foo 控件可以存在于 C# 命名空间 MyCompany.Controls.Core 中,Bar 控件可以存在于 C# 命名空间 MyCompany.Controls.Primitives 中,但两者都可以使用引用相同的 XAML 命名空间(http://mycompany.com/controls,此处使用 mycontrols 前缀作为别名)。