WPF: Tired of xmlns="clr-namespace …" ?!

I'm sure you all know the problem: When using custom objects or controls in XAML you need to add a xmlns:bla="clr-namespace:MyDotNetSpace" declaration to each XAML file (which can be thought of as the C# using statement).

Although this is now comfortabely supported by Visual Studio Intellisense, some other solution would be nicer to have..image

As I always want to do things like "Microsoft" does ;-), I thought of ways how to add my .NET namespaces into such nice looking Uri namespaces..

I found the solution for it, which is really easy:

[assembly:XmlnsDefinition("http://blogs.msdn.com/knom/wpf/XmlnsDemo", "Knom.WPF.XmlNs")]
namespace Knom.WPF.XmlNs

Just decorate your namespace with this XmlnsDefiniton attribute and map an Xml-namespace to your .NET namespace.

Now you can simply reference the namespace by using:


Tired of using the prefix (like my:..)? For this there're two tricks:

[assembly:XmlnsPrefix("http://blogs.msdn.com/knom/wpf/XmlnsDemo", "max:")]

This will specify a default prefix of max: for the xml namespace. If you drag in the control in the designer, this prefix will be generated for the namespace.

An interesting, but dangerous option is multiple .NET <--> XML namespace mappings: You can map different .NET namespaces into one xml namespace.

Consequently you can map YOUR .NET namespace into the default xaml namespace like this:

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

This way your namespace is now part of the XML namespace normally included as default namespace. So you won't need to specify ANY prefix for your classes. Disadvantage: The transparency which class is included in which assembly is lost..

Comments (3)

  1. Thank you. I broke some code out into a separate assembly and that assembly name had spaces in it. I think because of those spaces in the clr-namespace the URI was coming up as invalid. Adding the namespaces using the attributes corrected the issue.

  2. caywen says:

    I am very confused how a WPF/XAML application treats local namespaces. I am creating a WPF application, and I want my types to be referenced from the XAML, but I don’t want to do it the "clr-namespace" way. I am adding the assembly attribute "XmlnsDefinition" and adding the appropriate "xmlns:foo=…" attribute in the XAML. But it does not allow me to reference anything using "foo:". If I change the xmlns:foo="clr-namespace:…" then it works fine.

    What’s the deal? Does XAML not allow you to provide a normal namespace definition for your local types? How come we can specify "x:Class=" using local types, but none of the other XAML definitions allow you to do that?

    I’m utterly confused!

Skip to main content