Silverlight Tutorials Chapter 2: Introduction to Silverlight Application Development


Hope, you read my first chapter of the Silverlight Tutorial “Silverlight Tutorials Chapter 1: Introduction to Silverlight”. In that post, we learned about the very basic informations on Silverlight, it’s System Requirements, pre-requisite to create a Silverlight application, XAP file, XAML file and hosting a Silverlight application.

In this chapter we will first discuss on how to create a new Silverlight project and the structure of it. Later in this chapter we will discuss on UserControls and various ways of development. After reading this chapter you will be able to create a HelloSilverlight application and UserControls for your application.

 

How to create a new Silverlight Project?

If your development environment is ready then we can proceed towards creating a new Silverlight Application project. At the end of this part we will be able to run our first Silverlight application inside the browser.

1. Open your Visual Studio 2010 IDE

2. Select File > New Project or just press CTRL + SHIFT + N to open up the New Project dialog

3. Expand the “Visual C#” node and then go to sub node “Silverlight”

4. Select “Silverlight Application” in the right pane

image

5. Select proper location to store your application (let’s say, “D:\Sample Apps\”

6. Now enter a proper name for your project (call it as: SilverlightApps.HelloSilverlight)

7. Select the .Net Framework version from the combo box at the top (I am using .Net Framework 4.0 by default as I am using Visual Studio 2010) and click OK

8. In the next dialog make sure that “Host the Silverlight application in a new Web site” option is selected

image

9. Choose “Silverlight 4” as the Silverlight Version and hit OK

Wait for a while, Visual Studio will now create the first Silverlight solution for you to use which will contain a Silverlight Project and one Web Application Project to host your Silverlight application. Once done, you will see Visual Studio already created two XAML files (App.xaml & MainPage.xaml) for you inside the Silverlight Application project.

 

So for now your first Silverlight application has been created. Press F5 to run the application. It will open a browser Window with a blank page on that. Wow! What happened? Nothing is there!!! Don’t worry, everything is fine. We didn’t modify the default blank XAML page. Just right click on the browser page & you will see the Silverlight context menu on that.

 

image

 

 

What’s the Project Structure of Silverlight?

When you create a new Silverlight project, Visual Studio IDE creates two different projects for you (as you can see in the below picture). One is your main Silverlight project and the another is a Web application project which will host your Silverlight application (.xap file).

 

image

 

The main Silverlight project (SilverlightApps.HelloSilverlight) consists of App.xaml, App.xaml.cs, MainPage.xaml & MainPage.xaml.cs. I already discussed on those file in depth in previous chapter. The web project (SilverlightApps.HelloSilverlight.Web) consists of JavaScript file named Silverlight.js which is responsible for checking the Silverlight version in client side and also if the Silverlight plug-in is missing at the user end, it asks to install the required runtime from Microsoft site. The .aspx & .html pages are present in the root to host the Silverlight application. Your Silverlight application .xap file is located under the ClientBin directory inside the Web project.

 

 

Creating a “HelloSilverlight” Application

Now let us start modifying the “MainPage.xaml” by insertinga text “Hello Silverlight”. We will add one TextBlock control inside the Grid panel with it’s text property as “Hello Silverlight”.

 

But before going to add the content inside your page let me tell you that, you can add it in two ways: “Declarative approach in XAML” and “Programmatic approach in Code-Behind”. In declarative approach you have to add the Silverlight controls in the XAML page in XML format only with their properties as attributes. In other hand, you have to create the objects of the controls programmatically and have to set their properties.

 

First go with the Declarative Approach:

1. Open the file “MainPage.xaml” in Visual Studio
2. Inside the Grid tag add the following texts:

 
<TextBlock x:Name="txtTitle" Text="Hello Silverlight From XAML" FontSize="32"
           Foreground="Red" HorizontalAlignment="Center"/>

Your XAML page will now look like this:

 
<UserControl x:Class="SilverlightApps.HelloSilverlight.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"
             mc:Ignorable="d"d:DesignHeight="300" d:DesignWidth="400">
                <Grid x:Name="LayoutRoot" Background="White">
                    <TextBlock x:Name="txtTitle" Text="Hello Silverlight From XAML"
                               FontSize="32" Foreground="Red" HorizontalAlignment="Center"/>
                </Grid>
</UserControl>

3. Press F5 to run your application once again. Once the browser loads your Silverlight application you will see “Hello SilverlightFrom XAML” text appears inside the browser window.

image

 

Now, we will create the same from the code behind (programmatically). Assume that, we have not added the Text inside the XAML.

1. Open your “MainPage.xaml.cs” using the Visual Studio
2. There you will find the constructor of the MainPage class. Add the following lines of code after the call to the InitializeComponent() method:

 
// Create the instance of the textblock and set it's properties
TextBlock txtTitle = new TextBlock
    {
        Name = "txtTitle",
        Text = "Hello Silverlight From Code",
        FontSize = 32.0,
        Foreground = new SolidColorBrush(Colors.Red),
        HorizontalAlignment = HorizontalAlignment.Center
    };
// Add the textblock instance as the children of the "LayoutRoot"
LayoutRoot.Children.Add(txtTitle);

 

 

Let’s describe it in depth. First of all we are creating the instance of the TextBlock control and setting the Name, Text, FontSize, Foreground color etc. at the time of initialization. Then once the control is ready, we are adding it to the main panel i.e. the Grid layout panel inside the XAML named “LayoutRoot”.

 

After adding this your code will look like below:

 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
 
namespace SilverlightApps.HelloSilverlight
{
    public partial class MainPage : UserControl
    {
        public MainPage()
        {
            InitializeComponent();
 
            // Create the instance of the textblock and set it's properties
            TextBlock txtTitle = new TextBlock
                {
                    Name = "txtTitle",
                    Text = "Hello Silverlight From Code",
                    FontSize = 32.0,
                    Foreground = new SolidColorBrush(Colors.Red),
                    HorizontalAlignment = HorizontalAlignment.Center
                };
                
                // Add the textblock instance as the children of the "LayoutRoot"
                LayoutRoot.Children.Add(txtTitle);
        }
    }
}

 

3. Press F5 to run your application. You will now see your browser window opens with a text “Hello Silverlight From Code” inside it.

image

 

Note that, the TextBlock control has been added as a child element to the LayoutRoot panel which is a Grid. So, the question here is, what are the panels available in Silverlight where we can add child controls? Ok, for now just remember that there are several content holders (panels) available to hold any child controls like: Grid, Canvas, Border, StackPanel etc. In XAML pages the elements are maintained in a hierarchy like the HTML pages (DOM i.e. Document Object Model). This hierarchy allows us to nest different controls inside each other. I will discuss on this in depth in the next chapter.

 

Creating a Silverlight UserControl

In our last example we have seen, once we created the Silverlight project, the Visual Studio IDE has automatically created two XAML pages: App.xaml&MainPage.xaml. If you view the MainPage.xaml in depth, you will notice that it started with “UserControl” as the root element.

 
<UserControl x:Class="SilverlightApps.HelloSilverlight.MainPage". . . >
</UserControl>

Also, if you open the MainPage.xaml.cs file you will notice that the class itself inherits from the base class “UserControl”.

 
namespace SilverlightApps.HelloSilverlight
{
    public partial class MainPage : UserControl
    {
        public MainPage()
        {
            InitializeComponent();
        }
    }
}

So, what is that UserControl? UserControls are basic unit of reusable XAML like you use in asp.net. It is the root of your XAML and contain only one child as a control. Though that child may contain one or more other controls but the UserControl must have a maximum of one content control. UserControls are mainly created using XAML and then reused in various places.

 

How can I create a simple new Silverlight UserControl? Is it difficult to implement? Ummm… I will not tell you. Let us create a simple UserControl then. You will tell me whether it is difficult or simple.

Silverlight Tools for Visual Studio comes up with the default template for creating a basic UserControl. Now follow the steps to create it:

  1. Open your existing Silverlight application project (for this example, you can use the “HelloSilverlight” project just now we created)
  2. Right click on the Silverlight project “SilverlightApps.HelloSilverlight” and select Add -> New Item
  3. Select “Silverlight UserControl” from the right panel
  4. Enter a good name (here I am using “EmployeeView”) and hit enter

image

 

This will create the UserControl named “EmployeeView” with the default template layout and open up the XAML page in the IDE. If you look into the XAML code you will notice the following code:

 
<UserControl x:Class="SilverlightApps.HelloSilverlight.EmployeeView"
             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"
             mc:Ignorable="d"d:DesignHeight="300" d:DesignWidth="400">
     <Grid x:Name="LayoutRoot" Background="White">
     </Grid>
</UserControl>

We already discussed about each of the lines in the previous chapter (in “What is MainPage.xaml file” section). So, I will not cover it again. Now let us build our first UserControl to show the Employee’s FirstName, LastName& Department inside the UserControl XAML file. How to do that? Before doing it let us split our Grid panel into three Rows & two Columns (will discuss on this in next chapter):

 
<Grid x:Name="LayoutRoot" Background="White">
    <Grid.RowDefinitions>
        <RowDefinition/>
        <RowDefinition/>
        <RowDefinition/>
        </Grid.RowDefinitions>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="100"/>
        <ColumnDefinition Width="*"/>
    </Grid.ColumnDefinitions>
</Grid>

Now, lets add the TextBlocks inside the Grid, in specific Rows and Columns. In our case the left column will hold the “FirstName”, “LastName” and “Department” label. The second column will hold the informations according to the labels. Here is the XAML code for the same:

 
<UserControl x:Class="SilverlightApps.HelloSilverlight.EmployeeView"
             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"
             mc:Ignorable="d" Width="300">
    <Grid x:Name="LayoutRoot" Background="White">
        <Grid.RowDefinitions>
            <RowDefinition/>
            <RowDefinition/>
            <RowDefinition/>
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="100"/>
            <ColumnDefinition Width="*"/>
        </Grid.ColumnDefinitions>
        <TextBlock x:Name="LabelFirstName" Text="FirstName" Grid.Row="0" Grid.Column="0"/>
        <TextBlock x:Name="FirstName" Text="Kunal" Grid.Row="0" Grid.Column="1"/>
        <TextBlock x:Name="LabelLastName" Text="LastName" Grid.Row="1" Grid.Column="0"/>
        <TextBlock x:Name="LastName" Text="Chowdhury" Grid.Row="1" Grid.Column="1"/>
        <TextBlock x:Name="LabelDepartment" Text="Department" Grid.Row="2" Grid.Column="0"/>
        <TextBlock x:Name="Department" Text="Software Engineering" Grid.Row="2" 
                   Grid.Column="1"/>
    </Grid>
</UserControl>

 

You can see, I am using “Grid.Row” and “Grid.Column” attributes in each TextBlock. What does it mean? Grid.Row specifies the row number where to place the control. Similarly, Grid.Column specifies the column number. For example, if you use Grid.Row=”2” and Grid.Column=”4” to any element inside your Grid, the element control will be placed in 3rd Row and 5th Column of the Grid. You can think the Grid panel as a Matrix which has zero based index.

 

Our UserControl is ready now, but before running the application we need to put it inside the MainPage which loads at application load. You can do this in two different ways. One is using the XAML and the another is using the Code-behind file. In code behind it is very easy. You have to follow the same steps as we did in previous chapter to set the “Hello Silverlight” TextBlock, but if you want to set it in XAML you have to do a little trick for the first time. Let us discuss on this step-by-step:

 

First go with the Declarative Approach:

 

1. Open the file “MainPage.xaml” in Visual Studio
2. Add the following line inside the UserControl tag of the MainPage.xaml (after any xmlns line):

 
xmlns:uc="clr-namespace:SilverlightApps.HelloSilverlight"

 

 

Now, your MainPage.xaml will look like this (the bolder text I have inserted in the XAML):

 
<UserControl x:Class="SilverlightApps.HelloSilverlight.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:uc="clr-namespace:SilverlightApps.HelloSilverlight"
             mc:Ignorable="d"d:DesignHeight="300" d:DesignWidth="400">
    <Grid x:Name="LayoutRoot" Background="White">
    </Grid>
</UserControl>

Here, “uc” stands for pre-tag for specifying the namespace. You can use any name. We used “uc” to specify “UserControl” for better readability. Now inside the Grid control you can add the UserControl we have just created. Here is the code for the same:

 
<Grid x:Name="LayoutRoot" Background="White">
    <uc:EmployeeView Width="300" Height="60"/>
</Grid> 

 

Once you run your application now, you will see the following view of your first UserControl application:

 

image

 

Now let us create it from Code-behind. I assume that the control we just added inside the Grid has been removed from the XAML, that means your Grid panel has no child inside it. Create the instance of the EmployeeViewUserControl and add it as child to the LayoutRoot Grid:

 

 
// Create the instance of the EmployeeViewUserControl
EmployeeView empView = new EmployeeView{Width = 300.0,Height = 60.0,};
 
// Add the EmployeeViewUserControl as the child of the default panel "LayoutRoot"
LayoutRoot.Children.Add(empView);

 

Run your application and you will see the same output. The second approach is easy, am I right? Yup, for the first application it looks very easy enough. But when you write complex applications you will notice that the first approach is easier than the later. Why? Because, you will get more control over the design. You can see the output immediately in the preview sceen, also you can drag the control to position it properly in the panel. In some cases you will find it useful from code.  Depending upon your business need you have to decide where to create and add your UserControl.

 

Is it confusing? No, when you are sure that you have to dynamically load no. of UserControls based on your data you have to create and load it from the code behind. For the other cases, it will be easier to write inside the XAML.

 

Remember that, you can create as many instances of your UserControl and place it inside your XAML page. Once we discuss on the different types of panel and layout in next chapter you can get better visibility to that.

 


What next?

If you like this tutorial, don't forget to vote for it. Any Feedbacks/Suggestions are welcome.


If you have come this far, it means that you liked what you are reading. Why not reach little more and connect with me directly on Twitter , Facebook , Google+ and LinkedIn . I would love to hear your thoughts and opinions on my articles directly. Also, don't forget to share your views and/or feedback in the comment section below.

56 comments

  1. I have read all the 4 Chapters and it was excellent, awaiting for your next Article, will be happy if i get to know more about styling the controls and basic layout designing

    ReplyDelete
  2. Hi Rajesh,

    Thank you for the feedback. Will see it soon. Till then enjoy reading my other articles on Silverlight.

    Regards,
    Kunal

    ReplyDelete
  3. Great post. I have read another article from you. I will wait another article from you.

    ReplyDelete
  4. Excellent. Actually i am searching some articles to learn silver light.
    Finally i got a this.
    This article is just excellent. U r doing good job. Keep it up...
    Thank you....

    ReplyDelete
  5. Nice, very good starting tutorial and line by line explination andwalk through

    ReplyDelete
  6. NIce tutorial
    Thanks

    ReplyDelete
  7. Its Really good for Beginers to understand... God job Kunal

    Senthilkumar SV

    ReplyDelete
  8. Hey,

    Just wanted to say thanks as well, Bro. You certainly do teach Silverlight in a clear way. It is much appreciated.

    James Khouri

    ReplyDelete
  9. Thanks Kunal...It is best.Gaurav

    ReplyDelete
  10. Very nice...

    Thanks,

    ReplyDelete
  11. This is fantastic!

    ReplyDelete
  12. This article is really too good and helpful to beginners.

    ReplyDelete
  13. This article is really too good and very helpful to beginners.

    ReplyDelete
  14. Hi ,
    Thank you very much for these awesome Articles. I have a suggestion and need.
    Please make a simple tutorial of "Calling,Manuplating and binding Data from SQL Server in Silverlight."
    I am looking for a basic kind of technique for binding data from sql to Silverlight.

    Thank you again for these knowledge Articles.
    I am waiting for an article about it.

    ReplyDelete
  15. REally a wonderful tutorial..thanks

    ReplyDelete
  16. Hi Kunal,
    Thank you so much for this helpul article. it is the great effort.

    ReplyDelete
  17. really nice topic ! please make some more very very helpful dude.. regards : parasgreens@gmail.com

    ReplyDelete
  18. thanks man, ur tutorial is easy to learn.

    ReplyDelete
  19. very helpful...

    ReplyDelete
  20. I appreciate how you show the 2 methods for adding controls, and also explain when to use each. Very good tutorial.

    ReplyDelete
  21. i just want to know doubt..that i have just try to install the silverlight but the os cant able to install .. because its less memory space ..is silverlight must been install with separate computer ah its needs more memory space sir..


    soundarya ..coimbatore

    ReplyDelete
  22. Hi soundarya,

    Can you tell me in detail exactly what issue are you facing and what's your computer configuration? Are you able to get some log file or can you share me the final error screen?

    Regards,
    Kunal Chowdhury

    ReplyDelete
  23. GOod one!! easy to understand and well explained for Beginners

    ReplyDelete
  24. its really nice tutorial and your explanation is very good. tnxx

    ReplyDelete
  25. your explanation is really good . thx u

    ReplyDelete
  26. I recently started learning SilverLight and got to know about this portal. It really rocks...... Kudos to u Kunal...

    ReplyDelete
  27. this article was simply superb... thank you kunal...!

    ReplyDelete
  28. Very informative and exhaustive

    ReplyDelete
  29. Very Useful for a beginner .. a must read ..

    ReplyDelete
  30. Thanks for given this useful tutorial for beginners and we are expecting more from you

    ReplyDelete
  31. very intresting and good article could you please provide an article on dashboards creation using silverlight sir...

    ReplyDelete
  32. I have read your 4 articles it was very helpful for me.Very great effort.Please provide article on creating Dashboards using silverlight.

    ReplyDelete
    Replies
    1. Thanks for the feedback. What type of dashboard you are looking for?

      Delete
  33. Nice explanation with step by step guidance. It feels like having a live training. I am looking to create a dashboard for my application with the help of silver light. I am planning to have graphs in silver light. Can you provide any help related to this?

    Thanks.

    Regards,
    Shubham

    ReplyDelete
  34. Nice article Kunal,I want to develop BI dashboard on silverlight how can i start

    ReplyDelete
  35. where is Silverlight chapter 3

    ReplyDelete
  36. very well explained
    looking for chap 3

    ReplyDelete
  37. Can anyone give me link for next chapter.. ?

    ReplyDelete
  38. Hello sir
    I am using VS 2013.
    I just start to learn silverlight.
    To start I write very simple code but when i run that it show following the exception

    Unable to start program
    A null reference pointer was passed to the stub.

    Any solution?????

    ReplyDelete
    Replies
    1. set the default browser from google chrome to ie.

      Delete
  39. Good article! For more tutorials on silverlight, Check this site for indepth Silverlight tutorials. Go here if you’re looking for tutorials on Silverlight.

    ReplyDelete


 
© 2008-2016 Kunal-Chowdhury.com - Microsoft Technology Blog for developers and consumers | Designed by Kunal Chowdhury
Back to top