简体   繁体   中英

WPF XAML merge default namespace definitions

In a WPF application, you can create XmlnsDefinitions to map multiple namespaces from another assembly into one reference .

You can take advantage of that to map your own namespaces to the Microsoft default XmlnsDefinition, for example:

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

This way, you don't even need to add a reference to your namespace in the XAML file, because they are already mapped to the default "xmlns".

So, if I had a control called "MyControl", I can use it like this (without any namespaces or prefixes):

<MyControl />

My question is : Can I merge the default Microsoft namespaces into a single one?

For example: I want to get rid of the "xmlns:x" namespace by merging it into "xmlns". I would have to reference all the namespaces in " http://schemas.microsoft.com/winfx/2006/xaml " to " http://schemas.microsoft.com/winfx/2006/xaml/presentation ".

Like this:

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

So I can turn this:

<Window x:Class="MyProject.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    >

Into this:

<Window Class="MyProject.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    >

You can't override existing namespace mappings as they are already present in the standard assembies, but you can try merging all .NET namespaces into your own XML namespace. Like this:

[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")]
// ...

It may work (I haven't tried). Your XAML will look like this:

<Window x:Class="FoobarProject.MainWindow"
    xmlns="urn:foobar"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">

Note that you can't get rid of x namespace:

  1. It isn't mapped to .NET namespace, it's pure XML namespace and part of XAML language.

  2. Doing so would cause conflicts ( x:Name vs. Name ).

Speaking of conflicts, merging namespaces like this is asking for trouble. You are likely to run into name conflicts which these namespaces are designed to solve.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM