Gerard
Gerard

Reputation: 13397

Is it possible to declare a namespace in code behind

Is it possible to declare a namespace like:

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

In code behind, e.g. in the constructor.

public MainWindow()
{
    // ... here
}

Purpose: less verbosity; declare namespaces in one place and use inheritance.

EDIT: I tried adding

[assembly: XmlnsDefinition("http://mycompany/myapp", "clr-namespace:MyApp.Controls")]
[assembly: XmlnsPrefix("http://mycompany/myapp", "myc")]

to AssemblyInfo.cs but the build finishes with error "The namespace prefix "myc" is not defined".

So I use the attirbutes in the same project as where the xaml file is.

Upvotes: 3

Views: 1587

Answers (2)

Dan Puzey
Dan Puzey

Reputation: 34200

There's an attribute you can use in the code of your referenced assembly that maps a Uri to your code namespaces:

[XmlnsDefinitionAttribute("http://yournamespace/", "Your.Assembly.Namespace")]

You can include multiple of these attributes, typically in your AssemblyInfo.cs, allowing multiple code namespaces to be referenced by a single Uri namespace in Xaml.

For example, if you point a decompiler at the PresentationCore assembly, you can see attributes such as this at the assembly level:

[assembly: XmlnsDefinition("http://schemas.microsoft.com/netfx/2007/xaml/presentation", "System.Windows.Ink")]

This is how the Uri import gets mapped to code namespaces.

(Full disclosure: I have taken this answer from an earlier answer I made here for a similar question.)

Upvotes: 8

GazTheDestroyer
GazTheDestroyer

Reputation: 21241

No, namespaces are part of the XML standard and have nothing to do with xaml/.Net

If your namespaces were declared in code behind, then your XAML would not be a valid XML document.

Upvotes: 0

Related Questions