You are on page 1of 14

What is SilverLight ?

Silverlight is a web based technology, launched by Microsoft in April 2007. Silverlight


is considered as a competitor to Adobes Flash.
Silverlight applications are delivered to browsers in a text-based markup language
called XAML. One important difference between Flash and XAML is, Flash is a compiled
application where as XAML is text based. Search engines can analyze and index such content,
which is a huge benefit for webmasters.
For regular internet users, Silverlight is a browser plug-in that supports video, audio
and animations.
For web developers, Silverlight offers much more. Silverlight supports video and audio
files without need of much programming. It allows them to handle events from web pages
(like handle start/end of video playing etc)

Difference between Silverlight 1 and Silverlight 2?


Silverlight 1 is purely AJAX and Javascript based. All the code has to be written in
Javascript and XAML.
Silverlight 2 supports managed code. When Silverlight 2 runtime is installed, it installs
a limited version of .NET runtime on the client machine. This allows .NET programmers to
write managed code to be executed on the client PC and provide a better user experience to
the users. Of course, there is security and restrictions built in to it so that the code has limited
access to the client computer.
Developers must be aware that if the end user decline to install the .NET runtime on
their client computer, the Silverlight 2 applications will not run.

Difference between Silverlight and WPF?


Silverlight and Windows Presentation Foundation (WPF) are 2 different products from
Microsoft, but has lot of overlap. Silverlight is a sub set of WPF in terms of features and
functionality.
Silverlight is a Microsoft technology, competing with Adobes Flash and is meant for
developing rich browser based internet applications.
WPF is a Microsoft technology meant for developing enhanced graphics applications for
desktop platform. In addition, WPF applications can be hosted on web browsers which offers
rich graphics features for web applications. Web Browser Applications (WBA) developed on
WPF technology uses XAML to host user interface for browser applications. XAML stands for
eXtended Application Markup Language which is a new declarative programming model from
Microsoft. XAML files are hosted as discrete files in the Web server, but are downloaded to the
browsers and converted to user interface by the .NET runtime in the client browsers.
WPF runs on .NET runtime and developers can take advantage of the rich .NET
Framework and WPF libraries to build really cool windows applications. WPF supports 3-D
graphics, complex animations, hardware acceleration etc.

Tools required to develop Silverlight applications?


To run Silverlight applications in a web browser, you need to have Silverlight run time
installed on the client browser as a plug in. This is a light weight version of .NET runtime.
However, to develop a Silverlight application, you need something more.
Silverlight SDK
This include a set of tools required to compile and build Silverlight controls.
If you are comfortable writing HTML using notepad and compiling .NET applications
from console tools, then you just need the Silverlight SDK to develop Silverlight applications.
However, most people use some kind of IDE to develop applications faster. Microsoft
offers 2 separate tools to develop Silverlight applications:
1. Microsoft Expression Studio - this tool is meant for web designers to create rich visual
elements for Silverlight applications. Expression Studio is recommended for web designers
who create rich internet applications with enhanced visual content and graphics. There are
several features provided for creating enhanced graphics elements with lot of options to pick
color, font etc.
2. Microsoft Visual Studio - this is the integrated development environment from Microsoft
to develop .NET applications. Programmers can use Visual Studio to develop Silverlight
applications which require programming. Visual Studio allows programmers to develop
sophisticated Silverlight applications in any .NET language (like C#, VB.NET etc).
If you are using Visual Studio, you can download the Silverlight development tools
from here. This download include the Service pack1 for VS.NET and the Silverlight SDK.
Which tool to use - Expression Studio or Visual Studio ?
If your Silverlight application include just graphics and visual elements, then you can use
Expression Studio. However, if you are a programmer and if your Silverlight application
include programming logic, then you might want to choose Visual Studio.

Difference between Silverlight Runtime and Silverlight SDK


Silverlight Runtime is a plug-in for browsers to support Silverlight enabled
applications. If Silverlight runtime is not installed, browsers will not be able to run Silverlight
elements in the browser. You can set up your Silverlight tags such a way that your browser
will automatically prompt the user to download and install the Silverlight plug in when your
application is launched in the browser.
Installing the run time is a one time operation on the client. Once installed, it will be
automatically launched when any Silverlight application is loaded in the browser.
Silverlight SDK is a set of tools, documentation, samples and templates for the web
developers to help them easily develop Silverlight enabled applications. The SDK is not really
mandatory to develop Silverlight applications, however, SDK will make development much
easier.

What is XAML ?
XAML stands for eXtended Application Markup Language. XAML contain XML that is
used to declaratively specify the user interface for Silverlight or WPF applications.
For example, if you need to display a rectangle, this is the XAML you need to use:

<Canvas Width="500" Height="500" Background="White">


<Rectangle Canvas.Left="75" Canvas.Top="90" Fill="red"
Width="100" Height="100" />
</Canvas>

When the above xaml is executed, it will display a rectangle filled with red color. You
may notice is that XAML is very similar to HTML in nature.

"Hello World" Silverlight application


Open Visual Studio and select the menu "File" > "New" > "Project"
Select the Project Type as "Silverlight" under your favorite language and choose the template
"Silverlight Application". I have selected Visual C# as the tutorials here.
I have named my project as "MySilverlightApp" and have selected the option "Create
directory for solution" so that all my project files are organized within a folder structure
(Figure 1)
We need a web page to host the Silverlight components that we develop. Visual Studio
makes this job easier in the next step by prompting you to automatically create a website.
Choose the options as shown in the attachment (Figure 2)
You are ready to rock ! Just press OK and Visual Studio will create 2 projects and a
bunch of files for you. We will analyze some of the files created by Visual Studio in the next
chapter.
Figure 1

Figure 2
Files created by Visual Studio by default
When we create a new Silverlight application using Visual Studio 2008, it creates
several files by default. See the solution explorer immediately after creating a new Silverlight
project with a host website (Figure 3)

Figure 3
We will analyse some of the files.
AppManifest.xml
This file defines the assemblies that are deployed to the client applications
App.xaml
App.xaml is a file used by Silverlight applications to declare shared resources like
brushes, various style objects etc. Also, the code behind file of app.xaml is used to handle
global application level events like Application_Startup, Application_Exit and
Application_UnhandledException. (Similar to Global.asax file for ASP.NET applications)
When Visual Studio creates the app.xaml file automatically, it creates few event
handlers with some default code. You can change the code appropriately.
private void Application_Startup(object sender, StartupEventArgs
e)
{

}
private void Application_Exit(object sender, EventArgs e)
{

}
private void Application_UnhandledException(object sender,
ApplicationUnhandledExceptionEventArgs e)
{

}
For ASP.NET developers, the above code will look familiar. This is similar to the
aplication level event handlers in Global.asax.

Page.xaml file
When you create a Silverlight project using Visual Studio 2008, it creates a default
xaml file called "Page.xaml". This is just a dummy start page created by Visual Studio and it
does not contain any visible UI elements. The default content of the page.xaml file looks like
this:
<UserControl x:Class="MySilverlightApp.Page"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Width="400" Height="300">
<Grid x:Name="LayoutRoot" Background="White"></Grid>
</UserControl>
The above code shows a user control and a Grid control. The UserControl is a high
level control that holds all other UI elements in a xaml file.
The Grid control is used as a layout panel and it can hold other UI elements. All UI
elements in a .xaml control must be placed within a layout panel. There 3 different
types of layout panels available in Silverlight 2.0. You will learn more about layout controls in
a later chapter.
When you compile your Silverlight Application project, it will compile all .xaml files and
various other resources in to a single assembly file. This assembly file will have the
extension .xap and will have the same file name as your project name.
To place your Silverlight control in a web page, you must refer to this .xap file in your
web page. When the .xap file is referred in a web page, the default .xaml page will be shown.
Based on user actions, you may open or close various .xaml files included in your .xap
assembly (Silverlight Application project).

Build and run your Silverlight hello World application


It is time to build and run your first Silverlight application. Press Ctrl+F5 to build and
run your application. If everything is setup correctly, then Internet Explorer will be launched
automatically with your default page which hosts your Silverlight object.
Since you have not done much for your control, you will see a blank page opened in
the browser.
Go back to your Visual Studio and open your web page which hosts the Silverlight
object. In my sample project, the file is named "MySilverlightAppTestPage.aspx" and the
content of the file looks like this:

<%@ Page Language="C#" AutoEventWireup="true" %>

<%@ Register Assembly="System.Web.Silverlight"


Namespace="System.Web.UI.SilverlightControls"
TagPrefix="asp" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" style="height: 100%;">
<head id="Head1" runat="server">
<title>Test Page For MySilverlightApp</title>
</head>
<body style="height: 100%; margin: 0;">
<form id="form1" runat="server" style="height: 100%;">
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<div style="height: 100%;">
<asp:Silverlight ID="Xaml1" runat="server"
Source="~/ClientBin/MySilverlightApp.xap"
MinimumVersion="2.0.30523" Width="100%" Height="100%"
/></div>
</form>
</body>
</html>

Most of the stuff above look familiar to ASP.NET developers. Some of the lines that
need some attention are:

<asp:ScriptManager ID="ScriptManager1" runat="server">


</asp:ScriptManager>
<asp:Silverlight ID="Xaml1" runat="server"
Source="~/ClientBin/MySilverlightApp.xap" MinimumVersion="2.0.30523"
Width="100%" Height="100%" />

The second line defines the Silverlight control to be hosted in the web page. The
attribute "Source" defines the .xap file to be used by the web page. This .xap file contains the
XAML and code from your .xaml files and will be executed by the Silverlight plugin.
In the current sample, you have just one xaml file called Page.xaml. When you
compile the solution, this file is compiled into a special file (MySilverlightApp.xap) with the
extension .xap.

Getting started with XAML tags


Let us add a xaml tag to your Page.xaml file and see how it works.
Open page.xaml file from your Visual Studio project and place the following code
within the Grid element:
<Rectangle Fill="Blue" Width="100" Height="100"/>
Now compile and run the application. You can see a blue rectangle displayed in your
web page.
As demonstrated above, the elements in a Silverlight xaml page are declared using
XAML tags. Silverlight 2 offers several XAML tags including common form tags like textbox,
button etc and various other UI elements like rectangle.
One nice thing about Visual studio is, it will show you a preview of the page as you
type the xaml tags. When you complete typing the above xaml tags in your .xaml page, you
will see the design preview in Visual Studio as shown in Figure 4:
You can swap the position of the code and preview by pressing the icon with 2 arrows
in the middle of the screen (between the tabs "XAML" and "Design". Also, you can use the
icons on the right end between the code and design panes to change the position of the code
pane and design preview.
Figure 4
How to place a Silverlight control in a web page ?
Each Silverlight Application project can have multiple .xaml pages. When you create a
new Silverlight Application project, Visual Studio creates a default .xaml file called
Page1.xaml. To add more .xaml pages, right click on the project in the Solution Explorer and
select "Add" and "New Item". Then select "Silverlight User Control"
One or more Silverlight Applications can be placed in a web page using xaml tags as
shown below:
<asp:silverlight id="Xaml1" runat="server"
source="~/ClientBin/MySilverlightApp.xap" width="300" height="300" />
In the above tag, the attribute "source" represents the name of the xap file which is
the compiled output of the Silverlight project. The .xap files contains the compiled version of
all .xaml files included in the Silverlight Application project.
When you compile the Silverlight Application project, it will be compiled to an
assembly with the extension .xap. For example, if your Silverlight project name is
"MySilverlightControl", when compiled, it will produce the assembly
MySilverlightControl.xap
Each Silverlight project can have multiple .xaml files. Each .xaml file is like a page or
form by itself. When you place a Silverlight Application in a web page, only one .xaml control
will be visible at a time. Based on various user actions, you may dynamically open various
.xaml pages (Just like you open forms in a windows application).

How to set default .xaml page in a Silverlight control ?


Each Silverlight project can have multiple .xaml files. However, only one .xaml file will
be visible at a time.
When you create a Silverlight project in Visual Studio, it will create a .xaml file called
"Page1.xaml" by default and this .xaml control will be displayed by default when you open the
web page.
You can change the default .xaml page by setting the property
"Application.RootVisual".
To try this, add a .xaml file called "Page2.xaml" in your silverlight project.
Now, open your App.xaml.cs file in the Silverlight project. Look at the
Application_Startup event handler. There you can see the default .xaml page being set. To
change the default .xaml page, you have to specify the name of the class used in the .xaml
page and set it to the Application.RootVisual property as shown below:
private void Application_Startup(object sender, StartupEventArgs e)
{
this.RootVisual = new Page2();
}
After you change the value here, compile the application and run. When the web page
is opened, you can see that the new .xaml control is displayed in the web page.

How to open XAML pages from another XAML page ?


In a Silverlight application, you can have multiple XAML pages. When you use the .xap
file in the web page, only one XAML control will be displayed at a time. The default XAML file
displayed is determined by the following code in the App.xaml file:
this.RootVisual = new Page1();
You can change the above line to the class name of any oher xaml file to open that file
by default.
Another scenario is, you may want to open different xaml files from the default xaml
page. For example, consider that you have a xaml control that prompt user to enter login
information. After the login credentials are validated, you may want to redirect to another
xaml file when the user click the "Submit" button.
This can be done by setting the "Content" property of the xaml page.
private void SubmitButton_Click(object sender, StartupEventArgs e)
{
this.Content= new NewXamlPage ();
}
The above code shows how to set the "Content" property of the xaml control in the
button click event handler. When the user click on the submit button, the new xaml file
(NewXamlpage) will be opened and original xaml file will be recycled.

Open a specific xaml page from a Silverlight control


Each Silverlight application project may include multiple xaml pages. When you refer
to a .xap file from a web page, the xaml page set using the Application.RootVisual property
will be displayed by default.
There may be cases where you want different XAML files to be displayed when you
refer to the same .xap file from different web pages. You can do this by passing the xaml file
name or some other kind of identification using InitParameters property of the Silverlight
control. This property can be set to the Silverlight control from the web page. The value set
from web page will be read by the Silverlight control and appropriate xaml page will be
opened.
To demonstrate this, let us create a sample Silverlight project with the name
"OpenSpecificXaml". (You can read the steps to create a new Silverlight project.)
After you compile and build your project, place the Silverlight control in your web page
as shown below:

<asp:Silverlight InitParameters="PageName=Page1" ID="Xaml1"


runat="server" Source="~/ClientBin/OpenSpecificXaml.xap"
MinimumVersion="2.0.30923.0" Width="100%" Height="100%" />

In the above code, see the code:

InitParameters="PageName=Page1"

Here we are setting the property "InitParameters" with a key-value pair indicating
which xaml page we want to open by default.
Now, we will read this property in the App.xaml file and set the appropriate page to
the Application.RootVisual property. Here is the sample code to use in the App.xaml.cs to
achieve this:
private void Application_Startup(object sender, StartupEventArgs e)
{
IDictionary parameters = e.InitParams;
if (parameters == null)
{
// No parameter passed.. open the default xaml
this.RootVisual = new DefaultPage();
}
else if (parameters["PageName"] == "Page1")
{
this.RootVisual = new Page1();
}
else if (parameters["PageName"] == "Page2")
{
this.RootVisual = new Page2();
}
else
{ // Open the default xaml
this.RootVisual = new DefaultPage();
}
}
Layout controls in Silverlight
There are 3 different types of layout panels provided by Silverlight. The Grid control is
one of them.
These are the 3 different types of layout panels provided by Silverlight:
1. Canvas - Position child elements absolutely in x,y space.
2. StackPanel - Position child elements relative to one another in horizontal or vertical stacks.
3. Grid - Position child elements in rows and columns.
You have to add a layout panel to every xaml page we create. All other UI elements must be
added inside one of the layout panels. Each page can have exactly one layout panel control.

Layout panel controls in Silverlight – Canvas


Silverlight offers 3 panel controls which can be used to define the layout and
positioning of the controls in a page. Canvas is one of the available layout controls.
Canvas defines a area within which you can place other controls by specifying the x
and y coordinate position. It is possible to overlap multiple controls within a canvas. Contrary
to regular HTML, when controls are overlapped in a Canvas, overlapped controls can hide
other controls.
When controls are placed within a Canvas, the x and y coordinates must be specified
for each control using the attributes Canvas.Left and Canvas.Top
This sample shows how to place a rectangle control within a Canvas by specifying x
and y coordinates:

<Canvas Width="500" Height="500" Background="White">


<Rectangle Canvas.Left="25" Canvas.Top="40" Fill="green"
Width="100" Height="100" />
</Canvas>
The above xaml tags defines a rectangle, filled with green color, of size 100x100
pixels. The rectangle will be placed 25 pixels from the left of the Canvas and 40 pixels from
the top of the Canvas.
The below example shows 3 rectangles overlapped each other:
<Canvas Width="500" Height="500" Background="White">
<Rectangle Canvas.Left="25" Canvas.Top="40" Fill="green"
Width="100" Height="100" />
<Rectangle Canvas.Left="50" Canvas.Top="65" Fill="yellow"
Width="100" Height="100" />
<Rectangle Canvas.Left="75" Canvas.Top="90" Fill="red" Width="100"
Height="100" />
</Canvas>
The below images (Figure 5)shows how the output look like:

Figure 5
How to display image in a Silverlight control ?
In Silverlight, the image control can be used to display images. The usage is pretty
straight forward. The syntax of using Image control is shown below:
<Grid x:Name="Layout" Width="250" Height="250" Background="GREEN" >
<Image x:Name="MyImage" Source="~/basket.jpg" Stretch="Uniform" >
</Image>
</Grid>
Image.stretch Property
The Stretch attribute can have the following values:
1. None
This will do no modification on the size of the image. If the image size is more than
the size of the container, then the image will be cut to fit in the container.
2. Fill
In this case, the image will be expanded to fill the region of the container. The aspect
ratio (proportion of width and height) will not be maintained.
3. Uniform
This is the default value. In this case, the image will be resized to fit the container, but
the aspect ratio will be maintained. So, there may be blank space in the container depending
on the width and height of the image and container.
4. UniformToFill
In this case, the image will be resized and will fill the container, but aspect ratio will be
maintained by trimming some portion of the image if required.
Width and Height properties
The width and height properties of the image can be used to override the stretch
property. If width and height properties are specified, then Stretch property will be ignored.
Image.Clip property
The clip property of Image control can be used in Silverlight to make certain portion of
the image visible and hide some part of it.
See an example of how to display an image in a elliptical form:
<Grid x:Name="Layout" Width="200" Height="220" Background="YELLOW" >
<Image x:Name="MyImage" Source=" Images/AppleTree.png"
Stretch="Fill">
<Image.Clip>
<EllipseGeometry x:Name="Ellipse" RadiusX="100"
RadiusY="100" Center="100,110"/>
</Image.Clip>
</Image>
</Grid>
The above code will produce an image(Figure 6) like this:

Figure 6
How to drag and move an image or object in Silverlight ?
The control that you like drag or move with the mouse can be embedded within a
Border control and then handle the mouse down, up and move events to make the object
move within your layout panel.
See sample .xaml code:
<Canvas x:Name="LayoutRoot" Background="White">
<Border x:Name="border1" Canvas.Top="100" Canvas.Left="10"
MouseLeftButtonDown="border1_MouseLeftButtonDown"
MouseLeftButtonUp="border1_MouseLeftButtonUp"
MouseMove="border1_MouseMove">
<Image x:Name="MyImage" Source="images/Basket.png"
Stretch="Uniform" ></Image>
</Border>
</Canvas>
In the above code, a Border control is placed in the Canvas. The most important code
to note is:
MouseLeftButtonDown="border1_MouseLeftButtonDown"
MouseLeftButtonUp="border1_MouseLeftButtonUp"
MouseMove="border1_MouseMove"
See the code for the code behind class:
public partial class Page : UserControl
{
// Global variable to indicate if user has clicked border
// and started/stopped moving.
private bool moving = false;

private double offSetX;


private double offSetY;

public Page()
{
InitializeComponent();
}

private void border1_MouseLeftButtonDown(object sender,


MouseButtonEventArgs e)
{
// Left mouse button clicked within border. start moving.
moving = true;

Point offset = e.GetPosition(border1);


offSetX = offset.X;
offSetY = offset.Y;
}

private void border1_MouseLeftButtonUp(object sender,


MouseButtonEventArgs e)
{
// Left mouse button release. Stop moving.
moving = false;
}

private void border1_MouseMove(object sender, MouseEventArgs e)


{
if (moving)
{
// Get the new mouse pointer position
Canvas parent = (Canvas)this.border1.Parent;
Point p = e.GetPosition(parent);
double x = p.X - offSetX;
double y = p.Y - offSetY;
// Set the new position for the border control.
this.border1.SetValue(Canvas.LeftProperty, x);
this.border1.SetValue(Canvas.TopProperty, y);
}
}
}
How to pass parameters to Silverlight controls from ASP.NET pages ?
You can pass parameters from your aspx pages and html pages to the Silverlight
controls. This chapter explains how to pass parameters to Silverlight controls from your aspx
page and code behind files.
InitParameters
The Xaml page user control has a property called InitParameters. You can set a
value in the form of key-value pairs from your ASPX pages. Since this property accepts key-
value pairs, you can pass any set of string values.
How to set InitParameters
Example - Set InitParameters property from ASPX page:

<asp:Silverlight ID="Xaml1" runat="server"


Source="~/ClientBin/MySilverlightApp.xap"
InitParameters="City=Houston,State=Texas,Country=USA" Width="300"
Height="300" />
You can set this property from the code behind file of your ASPX page as well.
Example - Set InitParameters property from the code behind file:

Xaml1.InitParameters = "City=Houston,State=Texas,Country=USA";
How to retrieve the InitParameters value ?
The value you pass to a Silverlight control through the InitParameters property can be
retrieved from the Application_Startup even handler in the App.xaml page.
private void Application_Startup(object sender, StartupEventArgs e)
{
IDictionary parameters = e.InitParams;
this.RootVisual = new Page1();
Now, in most cases, you may want to pass this value to the xaml page itself instead of doing
anything with in it the App.xaml.
Pass parameters from App.xaml to other pages
To pass the parameters from the App.xaml pages to other pages, you must modify the
constructor of xaml page class to accept parameters.

private IDictionary<string, string> parameters = null;


public Page1()
{
InitializeComponent();
}
public Page1(IDictionary<string, string> p)
{
this.parameters = p;
InitializeComponent();
}
The above sample shows an additional constructor added which takes a parameter of
type IDictionary and then sets the value to a member variable.
Now go back to your App.xaml and pass the parameters to the page:
private void Application_Startup(object sender, StartupEventArgs e)
{
IDictionary parameters = e.InitParams;
this.RootVisual = new MainPage();
}

You might also like