首页 文章

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

提问于
浏览
2

在WPF应用程序中,您可以创建XmlnsDefinitions以将多个名称空间从另一个程序集映射到一个引用 .

您可以利用它将您自己的命名空间映射到Microsoft默认的XmlnsDefinition,例如:

[assembly: XmlnsDefinition("http://schemas.microsoft.com/winfx/2006/xaml/presentation", "MyLibrary.MyControls")]

这样,您甚至不需要在XAML文件中添加对命名空间的引用,因为它们已经映射到默认的“xmlns” .

所以,如果我有一个名为“MyControl”的控件,我可以像这样使用它(没有任何名称空间或前缀):

<MyControl />

My question is :我可以将默认的Microsoft命名空间合并为一个吗?

例如:我想通过将它合并到"xmlns"来摆脱"xmlns:x"命名空间 . 我必须引用“http://schemas.microsoft.com/winfx/2006/xaml " to " 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"
    >

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 名称空间:

    • 它没有映射到.NET命名空间,它是纯XML命名空间和XAML语言的一部分 .

    • 这样做会导致冲突( x:NameName ) .

    说到冲突,合并这样的命名空间就是在惹麻烦 . 您可能会遇到这些名称空间旨在解决的名称冲突 .

相关问题