Associating XAML namespaces to CLR namespaces

Take a look at the following (simple) XAML:

<UserControl x:Class="SilverlightApplication1.MainPage"
"" xmlns:x=""> <Canvas x:Name="myCanvas"> </Canvas> </UserControl>

When I started talking about XAML, I said that the default XAML namespace is associated to several controls. You might be a little curious on how this is done. By using Reflector, you’ll see that many of the Silverlight assemblies associate CLR namespaces to XAML namespaces through the XmlnsDefinitionAttribute:


You’ll typically find this attribute in most assemblies that have been thought with Silverlight and WPF in mind. Notice, though, that its use isn’t mandatory to map a CLR namespace to XAML namespace because Silverlight (and WPF) supports a special mechanism for doing that. For instance, suppose you’ve got a type called BeautifulGrid, defined in the CLR Test namespace, in a Dumb assembly. Now, when you build the assembly, you didn’t knew anything about the XmlnDefinitionAttribute. How can you use the BeautifulGrid in your XAML file? Here’s the answer:

<UserControl x:Class="SilverlightApplication1.MainPage"
"" xmlns:x="" xmlns:my="clr-namespace:Test;assembly=Dumb"> <Canvas x:Name="myCanvas"> <my:BeautifulGrid> </my:BeautifulGrid> </Canvas> </UserControl>

There are some interesting gotchas  you should keep in mind when using this syntax:

  • the clr-namespace key is separated from its associated value by a semi-colon (:) while the assembly part of the expression uses an equal sign (=)
  • this is one of those places where you *can’t* use white spaces for improved readability;
  • you can omit the assembly part if the namespace you want to use is in the same assembly as the “current” XAML file.

Even though Silverlight supports the XmlnsDefinitionAttribute, the truth is that it doesn’t really play an important role for using custom types in Silverlight. The recommended approach for using custom types in XAML is to use the clr-namespace approach I’ve showed above.

And that’s it for now. Stay tuned for more in Silverlight.


~ by Luis Abreu on November 19, 2009.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: