Thursday, December 20, 2007

How to Use Custom User Controls in Silverlight

Since Microsoft hasn't released an official library of controls for Silverlight, making and using your own is very important. This tutorial is going to show you how to import and add a custom control to your Silverlight application.

The code and examples in this post have been written using Silverlight 1.1 Alpha. This tutorial won't cover how to make user controls - just how to use them. Just like a classic cooking show, I've prepared a user control earlier that we'll be using. I've created a replica of the default Windows XP WPF button. The DLL that holds this control can be downloaded
here - feel free to use the button for whatever you want.

Let's start by adding the button using nothing but XAML. The first thing we need to do is get the namespace into the XAML code.

<Canvas x:Name="parentCanvas" xmlns="http://schemas.microsoft.com/client/2007" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:controls="clr-namespace:SOTCSilverlightControls; assembly=ClientBin/SOTCSilverlightControls.dll" Loaded="Page_Loaded" x:Class="SilverlightControlsTestApp.Page; assembly=ClientBin/SilverlightControlsTestApp.dll" Width="640" Height="480" Background="White" >
</Canvas>


This is the code from a default Silverlight application. I've added the following attribute to the canvas, which will let us reference the DLL containing our user controls.

xmlns:controls="clr-namespace:SOTCSilverlightControls; assembly=ClientBin/SOTCSilverlightControls.dll"
What you put after "xmlns", in this case "controls", is what you will use to reference the namespace. This can be anything you want (as long as it doesn't already exist).
The only control in that assembly is a Button, so let's put one of those on our canvas.

No comments: