How to create a Custom Control in Silverlight?


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 during first one and half year of my job. But when I started working on custom controls, I came to know the power of custom control and all the fear gone out of my eyes.

 

It's around 2 years, I am working on it and every time I am exploring some great stuffs. Though it's a long time since Silverlight launched; still, I am seeing the same fear on others and hence decided to write a good series on it (explaining all the details), 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.



32 comments

  1. Good One.. Thanks a lot.. looking for detailed article - about various styles

    ReplyDelete
  2. Thank you. I will continue posting about Custom Control in depth.

    ReplyDelete
  3. Durgaprasad BudhwanApril 5, 2011 at 12:55 PM

    Good job Dude !
    This is what I wanted.
    Please let me know when you are going to publish next article of this series.

    ReplyDelete
  4. Thank you. The next part of the series is already done. Will publish online soon.

    ReplyDelete
  5. I think I woiuld start off by explaining what a custom control actually is, and when one would need one, instead of just starting to build something.

    ReplyDelete
  6. Thanks Kristof for the suggestion. Point noted. Will update it soon. Appreciate your feedback.

    ReplyDelete
  7. What is the need of custom control?

    ReplyDelete
  8. Just wait for the 3rd and 4th part. I will explain it there.

    ReplyDelete
  9. How & when do u find time for all this? I work on SL too, hardly find time for writing about these things.

    ReplyDelete
  10. Ha ha ha... Tell me one thing... Did you find this article useful? If so, this energies me to write more and more for you and also manages time for that. :)

    ReplyDelete
  11. hi kunal,
    i am a beginner and just started off with silverlight. i recently found a couple of custom controls in silverlight for windows phone 7. i could hardly understand how it was really coded! this article really helped me get the base out of it.
    thank you very much :-)
    please do keep posting and please place links to the next post within this page also to navigate easily. found difficult with the silverlight tutorial navigation in this site.
    thank you

    ReplyDelete
  12. Thank you so much for the feedback and suggestion.

    ReplyDelete
  13. The aricle is simply superb......and useful to freshers also.

    ReplyDelete
  14. Nathália TorezaniApril 29, 2011 at 4:24 AM

    Hi, Kunal! My name is Nathália, I’m a journalist at iMasters (http://imasters.com.br/), one of the largest developer communities in Brazil. We are starting a plan to improve our content, by translating some great materials that we unfortunately can only find in English.
    We´d like to republish this article of yours.
    Can you contact me?

    ReplyDelete
  15. HI Kunal .
    Is there any way to make CustomControl only in Expression Blend4 . I need to make styles for Custom Control only in Expression Blend 4 .

    ReplyDelete
  16. Hi Debal,

    Yes, you can do that. Just design your control and then export it as CustomControl. Make sure that, if you want to add additional functionality to the control, you have to write code.

    ReplyDelete
  17. Hi Kunal, I found this article very useful.I am a beginner to Silverlight and want to have command over this in short span of time.I have joined MS recently and I am looking for tutorials to learn the things in better way. It will be great if you could provide me some resources.

    ReplyDelete
  18. Hi Vishrut,

    You may find a lots of tutorials here in my blog to start with.

    ReplyDelete
  19. Really good one....helped me a lot....

    ReplyDelete
  20. Good post for a beginner to work on Custom control

    ReplyDelete
  21. when you write "Basic to the Template" at a header you meant to say "Back to the Template" instead?

    ReplyDelete
  22. Awesome.Explained very neatly.

    ReplyDelete
  23. Hi Kunal
    I created a silverlight custom control referring your blog. How to create a silverligt custom control. Thanks a lot for that post.

    sldateselector.codeplex.com

    I want to expose a event something like DateSelectionChanged in custom control. How to achieve that.?

    Thanks a lot

    ReplyDelete
  24. Hi Nadun,

    Check out the complete article series on Silverlight Custom Controls here, which will give you an overview and tell you the way to implement it:


    How to create a Custom Control in Silverlight?
    How to design a Custom Control by editing the Part Template?
    How to implement Template Binding in Silverlight Custom Control?
    How to access Control Template parts from Code Behind?
    So what's the difference between Custom Control and User Control?

    I hope that it will help you. Don't forget to ask me question, if you still have doubts.

    Thanks & Regards,
    Kunal Chowdhury

    ReplyDelete
  25. i have two queries...

    when i implement the above code, i get an error message, that is

    "Error 1 The namespace 'CustomControl' already contains a definition for 'MyControl' "

    what is the error means??

    one more question...when i add the "silverlight Templated control", an error is showing..that is "unable to load metadata for assembly 'control class'"

    what this error means and what should i do to counter these 2 errors...

    ReplyDelete
  26. Sir , I want to know if I am setting my theme in App.xaml . would it globally work for the whole application. if not then is there any other option to have a template in my silverlight application

    ReplyDelete
    Replies
    1. Hi Deeksha,

      If you set it in App.xaml, that will be accessible through out the entire application unless you have a local style near to your control. For example, you have a button style in App.xaml. Now you created a different style for the button in your MainPage, another different style inside the LayoutGrid, and the other one in the StackPanel where the button is. In this case, it will assign the style from the StackPanel resource. If it fails to find the style there, it will move level up in the visual tree and search for specific style. If it finds it in LayoutGrid, or Page or at the last in App.xaml, it will assign it.

      Hope, this helps. Let me know if you still have any doubts.

      Regards,
      Kunal Chowdhury

      Delete
  27. Thanks for this nice article.. good one!!

    ReplyDelete


 
© 2008-2014 Kunal-Chowdhury.com | Designed by Kunal Chowdhury
Back to top