Click here to Skip to main content
Click here to Skip to main content

How to create a Custom Control in Silverlight

By , 5 Apr 2011
 

I am working on Silverlight since 3 years and during the initial period I had a fear on creating Custom control. I was more confident creating UserControls. But when I started working on custom control, I came to know the power of custom control. Currently, I am seeing the same fear on others and hence decided to write a series, which will be beneficial for beginners.

In this tutorial part, we will discuss on "How to create a Custom Control in Silverlight". This is very basic and will be helpful for a beginner. Don't hesitate to leave your feedback at the end. If you have any query/suggestion/feedback drop a line here. I will try to answer you as early as possible.

Creating a Silverlight Application Project

First of all, we need to create a Silverlight project. Assume, you already know about it. Just for your reference, create a new project. From the left panel, select Silverlight and chose "Silverlight Application" from the right panel. Give a proper name for your application and solution. Click ok to continue.

image

In the next screen, just press "OK". You can chose the version of Silverlight from that screen.

Creating a Custom Control

Now once your project is ready, it's time for us to create a Custom Control. In this chapter, we will just create a default control without any additional customization. We will customize our control on later part of the series.

image

To do this, right click on your Silverlight project, from the context menu select "Add" and from the second level context menu click "New Item". This will open the "Add New Item" dialog box.

As shown in the below screen shot, select "Silverlight Templated Control" and give you proper name to the control. Remember that, the "Silverlight Templated Control" is the template for Custom Silverlight control.

image

Click "Add" button to add the custom control into your project. Once the control creation is done, you will notice two things in the solution explorer. Expand the "Solution Explorer" and there you will find the following things:

  1. A "Themes" folder containing a file called "Generic.xaml". This is the default resource file for all of your styles for your controls.
  2. A "MyControl.cs" file, which is nothing but the class of your custom control. The class name is the control name.

Note that, if you create multiple controls the IDE will create multiple class files for you with the name of the control. But the resource file will be same. All styles and templates of your control will go into the same file.

image

The above screenshot will give you better visibility of the files that has been created in our demo application.

Know about the Class

Here we will discuss about the class of the Custom control. You will get detailed knowledge on the class in later part of the series. For now just know that, every control by default derives from base class called "Control". You may change the base class to other control depending upon your requirement.

Have a look into the basic code that has been generated for you by the IDE:

using System.Windows.Controls;
 
namespace CustomControlDemo
{
    public class MyControl : Control
    {
        public MyControl()
        {
            this.DefaultStyleKey = typeof(MyControl);
        }
    }
}

You will see the above code in the constructor. It takes the control style from the resource file and set it as the default style of the control. More on the class, we will discuss later.

Basic to the Template

You will find the basic template of the custom control in the Generic.xaml file. Open the file and you will find the below style inside the ResourceDictionary:

<Style TargetType="local:MyControl">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="local:MyControl">
                <Border Background="{TemplateBinding Background}"
                        BorderBrush="{TemplateBinding BorderBrush}"
                        BorderThickness="{TemplateBinding BorderThickness}">
                </Border>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

The first line describes the TargetType of the style. The second line declares the Template of the control. Third line sets the value of the template. The child of the value is your ControlTemplate. You can design your control template here.

One thing I want to tell you here is that, this is the default template of any control. You can add more style values before starting the template declaration. We will discuss this later.

Adding the Custom Control in Main Page

Let us add the custom control that we created to our main page. To do this, you need to add the XMLNS namespace in the XAML. In our case, it is the project name. Once you declare the namespace, you will be able to access the control easily.

<UserControl x:Class="CustomControlDemo.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:CustomControlDemo="clr-namespace:CustomControlDemo" mc:Ignorable="d"
    d:DesignHeight="300" d:DesignWidth="400">
 
    <Grid x:Name="LayoutRoot" Background="White">
        <CustomControlDemo:MyControl 
            Width="200"
            Height="200"
            Background="Yellow"
            BorderBrush="Red"
            BorderThickness="1"/>
    </Grid>
</UserControl>

The above code will explain you everything. There we added our custom control named "MyControl" with proper declaration of height and width. If you don't specify the height and width, it will take the whole screen of the application (only for our example).

If you run the application, you will not see anything rather than the blank screen. This is because the control has default transparent background. Hence, we added a background color, border brush and border thickness to the control in the above code.

image

Once you run the application now, you will see the above UI in your browser. The rectangle is the custom control that we created in this sample. If you modify the control template, it will change the UI here automatically.

What Next?

This was the basic discussion on custom control in Silverlight. In our next tutorial, we will see some more on Custom Control. Leave your feedback here, if you find this article helpful. Also, leave your queries and I will try to answer you as soon as possible.

Follow my blog for the next part of the series. Also find me on Twitter @kunal2383. You will get update there too. Thank you so much for reading my articles/tutorials. Happy Coding.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

_ Kunal Chowdhury _
Software Developer
India India
Member
Kunal Chowdhury is a Microsoft MVP (Most Valuable Professional) in Silverlight Technology, a Codeproject MVP & Mentor, DZone MVB (Most Valuable Blogger), Speaker in various Microsoft events, Author, passionate Blogger and a Software Engineer by profession.
 
He is currently working as a Software Engineer II in an MNC located at Pune, India. He has a very good skill over XAML, C#, Silverlight and WPF. He has a good working experience in Windows 7 application (including Multi-touch) development too.
 
He posts his findings in his technical blog. He also writes for SilverlightShow and Codeproject portal. Many of his articles were highlighted as "Article of the Day" in Microsoft sites.
 
He also has another website called Silverlight-Zone.com where he posts article links on Silverlight, Windows Phone 7 and XNA accumulated from various web sites to help the community grow on specified technologies.
 
You can reach him in his Blog : http://www.kunal-chowdhury.com
He is also available in Twitter : http://twitter.com/kunal2383

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
Questioncannot find stylesmembersumus5 Feb '13 - 18:06 
Hi Kunal, thank you for good article. I was trying to reach you through your web site, but could not do it, hope you will answer here.
 
I have Silverlight application project and Silverlight class library with my Custom Control. In the application project I have UserControl that uses my custom control from class library. My problem is UserControl cannot get styles (generic.xaml) from library project. The only solution that I found is to create resource dictionary in the app.xaml like this:
 
<Application.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="/CustomControls.Controls;component/Themes/generic.xaml"/>
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Application.Resources>
 

I tried to declare recourse dictionary in the UserControl.xaml file in the application project, but styles still are not available.
 
Could you please shed some light on this issue.
 
Thank you.
GeneralMy vote of 5memberm_taha_h4 Feb '13 - 21:31 
It was short, straight and helpful.
QuestionThank youmemberm_taha_h4 Feb '13 - 21:29 
Thanks a lot. The article was straight and helpful.
Questionc# -custom controlmemberMember 797927922 Jun '11 - 18:49 
Hi ur article was very good.....but can you help me out of how to create custom control in c#
AnswerRe: c# -custom controlmvpKunal_Chowdhury22 Jun '11 - 19:12 
You can't directly create a Custom control in C#. You must need the template to give a representation of the UI.
Silverlight 5 Tutorials :   1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9

GeneralMy vote of 5memberfolencao9 May '11 - 20:35 
very useful, good job
GeneralRe: My vote of 5mvpKunal_Chowdhury22 Jun '11 - 19:11 
Thanks.
Silverlight 5 Tutorials :   1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9

GeneralMy vote of 5mvpBrij5 Apr '11 - 19:24 
Great one!!
GeneralRe: My vote of 5mvpKunal_Chowdhury6 Apr '11 - 2:45 
Thanks buddy. BTW, the 2nd part of the series is available here[^].

Regards - Kunal Chowdhury | Microsoft MVP (Silverlight) | CodeProject MVP | Software Engineer
 
My Latest Blog Feed [04-April-2011]:  A Complete Guide to Expression Blend 4 Shortcut Keys   [^Blog^]

Appreciate your vote and feedback

GeneralMy vote of 5memberAnil_Saran5 Apr '11 - 17:48 
Really another great one and usefull article Smile | :)
GeneralRe: My vote of 5mvpKunal_Chowdhury6 Apr '11 - 2:44 
Thanks Anil. The 2nd Part of the series you can find here: http://www.codeproject.com/Articles/177389/How-to-design-a-Custom-Control-by-editing-the-Part.aspx[^]

Regards - Kunal Chowdhury | Microsoft MVP (Silverlight) | CodeProject MVP | Software Engineer
 
My Latest Blog Feed [04-April-2011]:  A Complete Guide to Expression Blend 4 Shortcut Keys   [^Blog^]

Appreciate your vote and feedback

GeneralMy vote of 5mvpAbhishek Sur5 Apr '11 - 9:23 
Cool work... buddy
GeneralRe: My vote of 5mvpKunal_Chowdhury5 Apr '11 - 16:55 
Thanks

Regards - Kunal Chowdhury | Microsoft MVP (Silverlight) | CodeProject MVP | Software Engineer
 
My Latest Blog Feed [04-April-2011]:  A Complete Guide to Expression Blend 4 Shortcut Keys   [^Blog^]

Appreciate your vote and feedback

GeneralNeeds FormattingmvpJohn Simmons / outlaw programmer4 Apr '11 - 23:55 
The code snippets are wrong. Look into using the <PRE> tag to fix them.
".45 ACP - because shooting twice is just silly" - JSOP, 2010
-----
You can never have too much ammo - unless you're swimming, or on fire. - JSOP, 2010
-----
"Why don't you tie a kerosene-soaked rag around your ankles so the ants won't climb up and eat your candy ass." - Dale Earnhardt, 1997

GeneralRe: Needs FormattingmvpKunal_Chowdhury5 Apr '11 - 4:35 
Yes Sir I know that. This is a blog feed and hence, I was not sure when it was fetched by CodeProject. I was continuously checking for it to come in the list, so that, I can modify it. But when it came, it was already modified by the editors. The new rule really troubling us a lot. D'Oh! | :doh:

Regards - Kunal Chowdhury | Microsoft MVP (Silverlight) | CodeProject MVP | Software Engineer
 
My Latest Blog Feed [04-April-2011]:  A Complete Guide to Expression Blend 4 Shortcut Keys   [^Blog^]

Appreciate your vote and feedback

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web01 | 2.6.130513.1 | Last Updated 5 Apr 2011
Article Copyright 2011 by _ Kunal Chowdhury _
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid