Silverlight Playground
about Silverlight and other Amenities

Using XmlDefinition and XmlPrefix to better organize namespaces

2010-03-15T19:06:42+01:00 by Andrea Boschin

I'm pretty sure you agree with me if I say that namespaces in XAML are the way to the hell. I mean the intricated jungle of xml namespaces, clr namespaces and prefixes you have to handle in a medium application. Every time you add a new control in the XAML, when it come from a different namespace, Visual Studio try to guess a good name for the prefix to use in XAML tags, and obviously it goes wrong.

The problem comes from the need of having a reference to an Assembly containing the clr namespace, and probably if you use only the wysiwyg editor of blend it is not a problem if the name is long and complicated, but when you start modify the markup by hand you often found that the same namespace has a different meaning in two different files.

The RC release of Silverlight 4.0 come with a solution to this great problem. The solution has the form of two attributes, valid in assembly scope, that grant the capability of having a xml namespace defined for a give clr namespace and a default prefix to be used from the IDEs. Here is an example of how to use them:

   1: [assembly:XmlnsDefinition("http://silverlightplayground.org/xaml/controls", "SilverlightPlayground.Controls")]
   2: [assembly:XmlnsPrefix("http://silverlightplayground.org/xaml/controls", "slpgControls")]

The XmlDefinition here specify a mapping between the xml namespace (the one starting with http://) and the clr namespace SilverlightPlayground.Controls. The XmlPrefix determine that the splgControls prefix have to be used every time a reference to this namespace have to be created. Here is the result of dragging an element to the designer surface:

   1: <UserControl x:Class="SilverlightPlayground.Test.MainPage"
   2:              xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
   3:              xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
   4:              xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
   5:              xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
   6:              xmlns:slpgControls="clr-namespace:SilverlightPlayground.Controls;assembly=SilverlightPlayground.Controls"  
   7:              mc:Ignorable="d" d:DesignHeight="300" d:DesignWidth="400">
   8:     <Grid x:Name="LayoutRoot" Background="White">
   9:         <slpgControls:MyControl />
  10:     </Grid>
  11: </UserControl>

I don't know if this is the final solution, but I'm sure it will be important to have more organization in XAML.

Categories:   News
Actions:   E-mail | del.icio.us | Permalink | Comments (0) | Comment RSSRSS comment feed

Add comment




  Country flag

biuquote
  • Comment
  • Preview
Loading