Silverlight Custom Control – I

January 14th, 2009 by Julien Palard

This article is my first about creating Custom Controls in Silverlight 2.
So let’s build a simple one :
You need :

  • A .cs file, named with your new Custom Control name
  • A directory named Themes
  • A generic.xaml file in it (just delete generic.xaml.cs if it was created)

Silverlight Custom Control Tree in Visual Studio

A basic custom control .cs file (the logic part):

using System.Windows.Controls;

namespace Custom_Control_1
{
    public class EditableTextBlock : Control
    {
        public EditableTextBlock()
        {
            DefaultStyleKey = typeof(EditableTextBlock);
        }
    }
}

Download this code: EditableTextBlock.cs

A basic custom control generic.xaml file (the graphic part):

<ResourceDictionary
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  xmlns:controls="clr-namespace:Custom_Control_1">
    <Style TargetType="controls:EditableTextBlock">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="controls:EditableTextBlock">
                    <Grid Background="AliceBlue">
                    </Grid>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
</ResourceDictionary>

Download this code: generic.xaml

Now, to test, you need to add the xmlns of your namespace, and add the usercontrol :

<UserControl x:Class="Custom_Control_1.Page"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:ctrl="clr-namespace:Custom_Control_1"
    Width="400" Height="300">
    <Grid x:Name="LayoutRoot" Background="White">
        <ctrl:EditableTextBlock></ctrl:EditableTextBlock>
    </Grid>
</UserControl>

Download this code: page.xaml

In the next article, we’ll see how to bind properties with TemplateBinding.
Don’t forgot to read the MSDN !

One Response to “Silverlight Custom Control – I”

  1. {Dev Tricks} » Blog Archive » Silverlight Custom Control - II : Properties Says:

    [...] {Dev Tricks} Blogging developper tips and tricks « Silverlight Custom Control – I [...]

Leave a Reply

You must be logged in to post a comment.