Silverlight Custom Control – I

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);
        }
    }
}

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>

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>

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

This entry was posted in silverlight and tagged . Bookmark the permalink.

One Response to Silverlight Custom Control – I

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

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>