Sunday, May 31, 2009

Silverlight how to: Add a user control to another user control

I'm starting to experiment with SilverLight and there's plenty of material out there, but some of the small details are really hard to find. The first application I'm working on requires a couple user controls, one embedded in the other and I spent a couple hours finding how to insert the user control into another control, then to the page, I thought it would be as easy as drag and drop but that didn't work, tried a few other things with no luck, turns out you have to add the namespace to the xaml, similar to the way you declare your controls in ASP.NET
The top xml of a user control (or the Page.xaml which is really just a user control) looks like this:

<UserControl x:Class="MyNameSpace.SomeUserControl"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Width="200" Height="300">

right after the last line with xmlns, you can type "xmlns:[prefix]=" (where [prefix] is the prefix you want to use in the xml to add your control, and make sure to add the = at the end); intellisense will do the rest, the first line of the drop down will contain the default namespace of your assembly, select that and you're good to go, it will look something like this:

<UserControl x:Class="MyNameSpace.SomeUserControl"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:prefix="clr-namespace:MyUserControl"
    Width="200" Height="300">

You can now start adding your control by typing <prefix: wherever you want to add your control and again intellisense will do the rest for you, you will be able to select any of the user controls that you have created previously under that namespace.
One last thing, if you will be referencing that user control from the code behind, you will need to name your control:

<prefix:MyUserControl Name="myControl" ></prefix:MyUserControl>

Doing so will give you strongly typed access to the instance of the control in your code behind, public members included

myControl.SomePublicMethod(someParameters);