WPF XAML 合并默认命名空间定义

4
在WPF应用程序中,您可以创建XmlnsDefinitions将来自另一个程序集的多个命名空间映射到一个引用中。
您可以利用这一点将自己的命名空间映射到Microsoft默认的XmlnsDefinition,例如:
[assembly: XmlnsDefinition("http://schemas.microsoft.com/winfx/2006/xaml/presentation", "MyLibrary.MyControls")]

这样,您甚至不需要在XAML文件中添加对命名空间的引用,因为它们已经映射到默认的“xmlns”。因此,如果我有一个名为“MyControl”的控件,我可以像这样使用它(不需要任何命名空间或前缀):
<MyControl />

我的问题是:我能将默认的Microsoft命名空间合并为一个吗?
例如:我想通过将“xmlns:x”命名空间合并到“xmlns”中来摆脱它。 我需要将“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"
    >

使用以下代码将AmazonEnvelope格式化为AU Scratchpad:string innerxml = "xsi:noNamespaceSchemaLocation="amzn-envelope.xsd" xmlns:xsi="w3.org/2001/XMLSchema-instance""; using (var writer = XmlWriter.Create(stream, settings)) { writer.WriteStartElement("AmazonEnvelope"); writer.WriteRaw(innerxml); writer.WriteEndElement(); } - jdweng
那个问题与我的问题无关。 - Pedro Henrique
我将我的UserControl放入了System.Windows.Controls中。但是它对我不起作用:[assembly: System.Windows.Markup.XmlnsDefinition( "http://schemas.microsoft.com/winfx/2006/xaml/presentation", "System.Windows.Controls" )]看起来设计师能够看到我的类,但编译器却不能。错误:The tag 'ContentViewer' does not exist in XML namespace 'http://schemas.microsoft.com/winfx/2006/xaml/presentation' - Denis535
1个回答

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 命名空间:
  1. 它不是映射到 .NET 命名空间,而是纯 XML 命名空间和 XAML 语言的一部分。

  2. 这样做会引起冲突(x:Name vs. Name)。

说到冲突,合并命名空间可能会引发麻烦。您很可能会遇到这些命名空间旨在解决的名称冲突。

愚蠢的网络库总是希望默认命名空间作为最后一项。 - jdweng
"无法覆盖现有的命名空间映射,因为它们已经存在于标准程序集中。我应该早点想到这个问题。" - Pedro Henrique

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接