在WPF应用程序中,您可以创建XmlnsDefinitions以将多个名称空间从另一个程序集映射到一个引用。
您可以利用它将自己的命名空间映射到Microsoft默认的XmlnsDefinition,例如:
[assembly: XmlnsDefinition("http://schemas.microsoft.com/winfx/2006/xaml/presentation", "MyLibrary.MyControls")]
这样,您甚至不需要在XAML文件中添加对命名空间的引用,因为它们已经映射到默认的“xmlns”。
所以,如果我有一个名为“MyControl”的控件,我可以像这样使用它(没有任何名称空间或前缀):
<MyControl />
我的问题是:我可以将默认的Microsoft命名空间合并为一个吗?
例如:我想通过将它合并到“xmlns”来摆脱“xmlns:x”命名空间。我必须将“http://schemas.microsoft.com/winfx/2006/xaml”中的所有名称空间引用到“http://schemas.microsoft.com/winfx/2006/xaml/presentation”。
像这样:
[assembly: XmlnsDefinition("http://schemas.microsoft.com/winfx/2006/xaml/presentation", "System...")]
[assembly: XmlnsDefinition("http://schemas.microsoft.com/winfx/2006/xaml/presentation", "System...")]
...
所以我可以转过来:
<Window x:Class="MyProject.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
>
进入这个:
<Window Class="MyProject.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
>
答案 0 :(得分:3)
您不能覆盖现有的命名空间映射,因为它们已存在于标准程序集中,但您可以尝试将所有.NET命名空间合并到您自己的XML命名空间中。像这样:
[assembly: XmlnsDefinition("urn:foobar", "System.Windows.Controls")]
[assembly: XmlnsDefinition("urn:foobar", "System.Windows.Documents")]
[assembly: XmlnsDefinition("urn:foobar", "System.Windows.Shapes")]
// ...
[assembly: XmlnsDefinition("urn:foobar", "FoobarLibrary.Controls")]
// ...
它可以工作(我还没试过)。您的XAML将如下所示:
<Window x:Class="FoobarProject.MainWindow"
xmlns="urn:foobar"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
请注意,您无法摆脱x
命名空间:
它没有映射到.NET命名空间,它是纯XML命名空间和XAML语言的一部分。
这样做会导致冲突(x:Name
与Name
)。
说到冲突,合并这样的命名空间就是在惹麻烦。您可能会遇到这些名称空间旨在解决的名称冲突。