Saturday, December 18, 2010

Using XML namespaces in WPF

When referencing controls from another assembly in XAML, you probably use the xmlns:myAlias="clr-namespace:MyNamespace;assembly=MyAssembly" syntax.

Last week I discovered you also have another option, you can use an Uri instead of a namespace reference thanks to the XmlnsDefinition attribute. (Read more about this attribute on MSDN). It allows you to map a XAML namespace to one ore more assembly namespaces.

So how do you use it?

  1. Open the AssemblyInfo.cs file under the Properties folder of your project.
  2. Add the following line for each namespace in your assembly you want to map:
   1:  [assembly: AssemblyTitle("WPF Namespace Sample")]
   2:  [assembly: AssemblyDescription("")]
   3:  [assembly: AssemblyConfiguration("")]
   4:  [assembly: AssemblyCompany("")]
   5:  [assembly: AssemblyProduct("WPF Namespace Sample")]
   6:  [assembly: AssemblyCopyright("Copyright ©  2010")]
   7:  [assembly: AssemblyTrademark("")]
   8:  [assembly: AssemblyCulture("")]
   9:  [assembly: XmlnsDefinition("http://myApp/schemas/2010/xaml", "WPF.Samples.Controls")]
  10:  [assembly: XmlnsDefinition("http://myApp/schemas/2010/xaml", "WPF.Samples.Commands")]

You can use this reference then inside another project:

   1:  <UserControl    
   2:  xmlns=""   
   3:  xmlns:x=""   
   4:  xmlns:wpfSample="http://myApp/schemas/2010/xaml"     >

No comments: