« Great WPF hands on lab posted for an Outlook 2007 visual clone | Main | CompositionTarget performance »

Cheap and Easy WPF clr-namespace references.

(inspired by a forum post)

Tired of the Xaml syntax:

xmlns:local="clr-namespace:Blah.Yawn.Zzzzz"

that you add to every Xaml file that you create? Worse yet is that you end up adding multiple as you're referencing a bunch of auxiliary WPF pages, controls, types, etc.... so you have 3, 4, etc. of these. Yuck.

xmlns:local1="clr-namespace:Blah.Yawn"

xmlns:local2="clr-namespace:Blah.Yawn.Zzzzz"

xmlns:local3="clr-namespace:Blah.Yawn.Sleepy"

xmlns:local4="clr-namespace:Blah.Yawn.Snooze"

There's an easier way if you own the assemblies and you don't need to reference types in the main executable assembly!

If you don't (own them or you haven't broken them out into multiple assemblies), then you'll have to stick with the standard syntax, which requires one namespace per xmlns declaration.


Again, note that this only works for referenced assemblies.


Go to the assembly where your controls are located and add this assembly attribute to the AssemblyInfo.cs file:

[assembly: XmlnsDefinition("http://www.wiredprairie.us/WPF", "WiredPrairieUS.Controls")]

The xmlnamespace (first parameter) is up to you and should be unique (often your companies web site address followed by some schema. It doesn't really need to exist, just be unique to your product/component). The second parameter should map to the namespace where your types you want reference from Xaml are located. In this example, I've created some WPF controls and placed them in the WiredPrairieUS.Controls namespace.

You can reuse the same xmlns multiple times with different CLR namespaces if your types are in multiple namespaces. Maybe for example, I have a WiredPrairieUS.Controls.Advanced namespace:

[assembly: XmlnsDefinition("http://www.wiredprairie.us/WPF", "WiredPrairieUS.Controls.Advanced")]


Then, go back to the ordinal Xaml file that is using these types and add to the namespace declarations:

<Window
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local=
http://www.wiredprairie.us/WPF

That's it. You don't need to declare multiple xml namespaces to reference types in different CLR namespaces as they are automatically imported by the Xaml parser/compiler (it checks the referenced assemblies for the attribute above).

Nice.

If you're developing components for reuse/resale. Please consider adding this to your assemblies and documenting it if you haven't already.

Help support my web site by searching and buying through Amazon.com (in assocation with Amazon.com).