Xml namespace simplified in Silverlight 4.0

 

A feature added to Silverlight 4 that has not received much attention is the introduced support for the XmlnsDefinition and XmlnsPrefix attributes in custom assemblies. These attributes has been supported in WPF since day one, and has finally made their way into Silverlight as well.

The XmlnsDefinitionAttribute is used for mapping one or more CLR namespaces to one or more XML namespaces. The benefit of doing so is that
1) The user does not have to think or know about the CLR namespaces or assembly names when adding xmlns imports in XAML files
2) Because you can map several CLR namepaces to a single XML namespace, you can get away with a single XML namespace in your XAML files instead of one pr. CLR namespace when referencing components in your custom assemblies.

You typically define the XmlnsDefinitionAttribute in the AssemblyInfo.cs-file like so:

[assembly: XmlnsDefinition("http://schemas.mycompany.com/silverlight","MyCompany.Windows.Controls")]
[assembly: XmlnsDefinition("http://schemas.mycompany.com/silverlight", "MyCompany.Windows.Behaviors")]

Then, in a XAML file, you can simply add an xmlns import like this;

<UserControl x:Class="SilverlightApplication2.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:myCompany="http://schemas.mycompany.com/silverlight"

and now you can access the types specified in MyCompany.Windows.Controls and MyCompany.Windows.Behaviors throught the myCompany xmlns prefix.

Further, you can use XmlnsPrefixAttribute to specify a default prefix associated with a XML namespace. This prefix is used by the Visual Studio and Blend designer when you drag/drop custom components from the toolbox onto the designer surface.

[assembly: XmlnsPrefix("http://schemas.mycompany.com/silverlight","myCompany")]
[assembly: XmlnsDefinition("http://schemas.mycompany.com/silverlight","MyCompany.Windows.Controls")]
[assembly: XmlnsDefinition("http://schemas.mycompany.com/silverlight", "MyCompany.Windows.Behaviors")]