Try an online Silverlight class for free!
Additional Resources

The Silverlight Framework

In this lesson of the Silverlight tutorial, you will learn...
  1. How Microsoft Silverlight compares to Windows Presentation Foundation (WPF).
  2. To use various tools to create Silverlight applications.
  3. To write code in Silverlight applications using JavaScript and .NET Framework programming languages.
  4. About Windows Live Services that compliment Silverlight.
  5. About the controls that Microsoft provided for integrating Silverlight with ASP.NET.
  6. To use Silverlight from an ASP.NET AJAX page.
  7. To create a Silverlight application.

This lesson will introduce you to the inner workings of a Silverlight application.

Overview

Microsoft Silverlight is the latest development offering from Microsoft and a logical progression of Microsoft technologies.

Before Silverlight

Microsoft technologies progressed from separate and isolated development technologies to Active Server Pages (ASP), their first dynamic Web development technology. To stay competitive, Microsoft decided to redesign and consolidate all of their development technologies into a single platform, the .NET Framework.

One facet of the .NET Framework is ASP .NET. ASP .NET is an extremely powerful Web development environment but, by default, the bulk of the processing occurs on the server. Web applications will perform better if more processing occurs on the client.

To improve performance, Microsoft introduced ASP.NET AJAX to extend the client scripting capabilities and improve performance. However, the downside to processing with JavaScript is that JavaScript is executed by the user's browser, hence Microsoft is at the mercy of the browser vendor to correctly interpret and execute the JavaScript in ASP.NET AJAX.

Enter Silverlight

In an effort to take their technologies a step further, Microsoft began studying how they could gain control of the ASP.NET AJAX client-side environment and, at the same time, improve the technology. Microsoft also wanted to determine how to offer the same ability to create incredible user interfaces on the client-side that Windows Presentation Foundation (WPF) offers. As a result, Microsoft created a new downloadable plug-in technology that extends the ASP.NET AJAX environment significantly and, at the same time, incorporates much of the functionality and rendering capabilities of WPF. The resulting technology was originally named "WPF/E" (Windows Presentation Foundation / Everywhere) and was later renamed to Silverlight.

Silverlight vs. WPF

Silverlight is a subset of Windows Presentation Foundation that also extends and uses many of the features and aspects of ASP.NET AJAX. Silverlight's strengths lie in its portability over the Web. However, because it must work across platforms and browsers, it cannot take advantage of or be reliant upon any particular environment or platform. This limits its ability to provide the advanced 3D graphic features, speech and voice recognition, recording, and other features that WPF provides.

Furthermore, for security reasons, Silverlight has limited access to the host machine, which further limits its capabilities.

Silverlight Performance

Silverlight has a speedy rendering engine. There are a couple experiments out there on the Web that illustrate the performance advantages of Silverlight. The bouncing balls experiment, located at http://bubblemark.com, is a great example and can be used to compare rendering speeds of the most popular competitive development environments. Be sure to pick the Silverlight 2.0 option.

Installing Silverlight

The Silverlight plug-in can be downloaded and installed directly. Users are only required to have a supported operating system and supported Web browser installed to use Silverlight applications. All other requirements to run a Silverlight application are embedded within the Silverlight plug-in. The Silverlight 2 plug-in installation screen is shown in the figure below.

The installation screen shown when Silverlight 2 installs successfully is shown in the figure below.

As a developer with Visual Studio 2008 installed, you will want to download and install the Silverlight 2 Tools for Visual Studio 2008 SP1. This download includes the Silverlight 2 plug-in, the Silverlight 2 software development kit (SDK), and the tools for Visual Studio 2008. The Silverlight plug-in installed by the Silverlight 2 Tools is a special "developer-only" build which includes more debugging information than the end-user runtime. The Silverlight 2 Tools for Visual Studio 2008 installation wizard is shown in the figure below:

Silverlight Tools

The two most common Silverlight design and development tools are:

  1. Visual Studio 2008 - provides the ability to build Silverlight applications using XAML and offers only a read-only visual designer.
  2. Expression Blend 2 - provides the ability for designers to graphically build Silverlight applications.

There are a couple of other Silverlight tools available:

  1. Lunar Eclipse - a Moonlight design tool created by open source developers that runs locally on Linux.
  2. Eclipse4SL
    • When Silverlight 2 was released, Microsoft announced that it was supporting additional tools for developing Silverlight applications by providing funding to a company named Soyatec. Soyatec is leading a project to integrate Silverlight development capabilities into the Eclipse IDE. They plan to release this project under the Eclipse Public License Version 1.0. It is quite possible that this IDE will have a build available for the Mac, which would make Silverlight development possible on the Apple platform.

Silverlight Languages

The Silverlight plug-in offers a CLR execution environment and a .NET Framework base class library (BCL) that is hosted in the user's browser and is used to execute code. Silverlight is a progression of ASP.NET AJAX. ASP.NET AJAX extends the capabilities of JavaScript through a JavaScript library so that JavaScript is more object oriented and provides more functionality. The Silverlight execution engine further extends JavaScript and the browser-hosted execution environment.

Dynamic Language Runtime (DLR)

In version 1.0 of Silverlight, the only language available was JavaScript. Version 2 extends the execution environment and provides the ability to program Silverlight applications using several more advanced programming languages.

DLR Console

As a method of testing the DLR and prototyping Silverlight code and applications, Microsoft developed the DLR Console. Microsoft deployed the DLRConsole to Microsoft CodePlex and made it freely available for developers to extend and experiment with. The DLRConsole is available at http://silverlight.net/themes/silverlight/community/gallerydetail.aspx?cat=sl2. The DLR Console version that is available on CodePlex supports prototyping XAML using JScript and Python. The DLR Console is shown in the figure below:

C#

C# was developed from concepts of many previous programming languages including Java and C++. C# was created by Microsoft specifically to create .NET Framework applications and is fully object oriented.

NOTE: This course will use C# as the language of choice in most demos and labs.

Visual Basic / VBx

Visual Basic, currently in version 9.0, is not a dynamic programming language. However, version 10.0 (code-named VBx), which is under development, will be a new dynamic version of Visual Basic ideal for creating Silverlight applications.

JavaScript

While JavaScript is powerful and useful in traditional web development, it is not the best choice for Silverlight 2 applications.

IronPython

IronPython (see footnote) is a dynamic version of the Python programming language designed for use in Silverlight 2. Coverage of the IronPython programming language is beyond the scope of this course.

IronRuby

IronRuby (see footnote) is another dynamic programming language that is designed for use in Silverlight 2 and was modeled after the Ruby programming language. Coverage of the IronRuby programming language is beyond the scope of this course.

Windows Live Services

Microsoft has revamped their suite of online tools and utilities. For instance, Hotmail has been redesigned and renamed "Windows Live Mail." Several new services designed for Silverlight are currently under development.

One such online utility specifically targets Silverlight developers: the Silverlight Streaming service. The Silverlight Streaming service is used to host and test Silverlight applications. The Silverlight Streaming service (see footnote) is a free service and is available at https://silverlight.live.com/.

Microsoft and other vendors are also actively developing new online applications using Silverlight. One cool example of Silverlight is the Tafiti search and research tool. The figure below illustrates the Tafiti utility:

The original version of Tafiti provided a fun (if not too useful) tree view that displayed search results in an expanded literal tree view as shown in the figure below. The tree can be grown to display more branches and leafs or shrunk using the slider at the bottom of the page:

Example Implementations

Microsoft will be redesigning other services to take advantage of Silverlight going forward including Windows Live Search Maps, Windows Live SoapBox, the entire Microsoft Web site and MSDN Web site, and all new software services such as SQL Server 2008 Data Services and Office Live.

A multitude of vendors beyond Microsoft have already implemented Silverlight to create incredible user experiences. Two very popular examples that are guaranteed to generate excitement in the industry are the Hard Rock Cafe Web site and the 2008 Olympics Web site.

The Hard Rock Cafe Web site includes pages that can be used to browse the entire Hard Rock rock-n-roll memorabilia collection using the brand new Microsoft Deep Zoom technology combined with Silverlight. The Hard Rock memorabilia page is shown in the figure below and is located at http://memorabilia.hardrock.com/.

Another impressive example is the use of Silverlight for videos on 2008 Olympics Web site. Click one of the thumbnails to launch a video.

Microsoft PopFly

Another service that should be noted here is Microsoft Popfly. Popfly uses Silverlight and allows users to create games, mashups, mashup applications, and Web pages online. A mashup is an online application that a user can create through visual tools with no programming. Microsoft Popfly is located at http://www.popfly.com. The figure below shows the Popfly Web site:

Popfly also provides an explorer that can be installed and integrated with Visual Studio as shown in the figure below:

Once the Popfly explorer is installed, new Popfly Web sites can easily be created using Visual Studio. The New Web Site dialog with the Popfly Web Site option selected is shown in the figure below:

Silverlight ASP.NET Controls

ASP.NET is processed on the server. ASP.NET AJAX is also processed on the server through the ASP.NET page event life cycle; however, much of the processing is offloaded on to the client.

Once a Silverlight application is delivered from the server to the client, the processing is handled by the client. Calls can be made to the server or to a Web service but, by default, the application is executing in an isolated and independent environment. This means less demand on the server and speedier results for the user.

There are times when an application will benefit from merging the server-side and client-side worlds so that postbacks do occur to the server. For instance, a Silverlight application that must continually be updated from server-side content may benefit from postbacks. Additionally, completely redesigning a Web application around a new technology is a time-consuming and considerable task. Many ASP.NET and ASP.NET AJAX applications that are already developed, deployed, and stable may benefit from integrating Silverlight without being fully redesigned. Microsoft realized the need to merge the two worlds of Web computing and released some controls to do so in the ASP.NET Extensions.

The Microsoft ASP.NET Extensions include new features and functionality that are now integrated into .NET 3.5 Service Pack 1.

The asp:Silverlight Control

The Silverlight framework provides a generic class, or type, for working with XAML, the System.Web.UI.SilverlightControls.Silverlight control. The asp:Silverlight control is used to insert XAML into an ASP.NET AJAX page in a generic manner. The asp:Silverlight control is typically extended through JavaScript, managed code, or dynamic code to provide a specialized implementation of the control. The most commonly used attribute of the asp:Silverlight control is the Source attribute. The Source attribute identifies the XAML file to include in the page. The asp:Silverlight control only exposes three minimal events with one of those fired upon an error and one fired upon the XAML loading.

An example of including XAML in an ASP.NET AJAX page using the asp:Silverlight control is shown in the code listing below:

Code Sample: TheSilverlightFramework/Demos/aspSilverlight/Default.aspx

<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>
<%@ 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">
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
 <asp:ScriptManager ID="ScriptManager1" runat="server">
 </asp:ScriptManager>
 <div>
  <asp:Silverlight ID="Silverlight1" runat="server" Height="400px" Width="600px" Source="~/Scene.xaml"></asp:Silverlight>
 </div>
</form>
</body>
</html>

The Source attribute of the asp:Silverlight control can also point to a XAP file. A XAP file is a ZIP-compressed file containing a Silverlight application - including XAML files and compiled code-behind assemblies. You will learn more about XAP files later in this course.

The asp:MediaPlayer Control

The asp:MediaPlayer control is ASP.NET Extension that makes it easy to integrate audio and video into an ASP.NET or ASP.NET AJAX application without hand coding XAML or JavaScript.

Silverlight supports Windows Video (WMV), Windows Media Audio (WMA), and MP3 media formats.

Properties, Events, and Methods

The asp:MediaPlayer control inherits from the System.Web.UI.SilverlightControls.Silverlight control and, as such, includes all of the properties, events, and methods included in the asp:Silverlight control. It also includes a number of its own properties and methods.

The most commonly used properties are the MediaSource and the MediaSkinSource properties. As their names imply, the MediaSource property is used to identify the URL, or location, of the media file that is to be played by the asp:MediaPlayer control and the MediaSkinSource property is used to identify the skin, which can be predefined or custom, that the asp:MediaPlayer control should display while playing the media file.

The asp:MediaPlayer control also supports a number of built-in events including the onClientMediaOpened event and the onClientChapterStarted event.

The asp:MediaPlayer control is easy to use right out of the box. Once the ASP.NET Extensions Preview is installed, the asp:MediaPlayer control can be added to ASP.NET pages declaratively or by dragging and dropping the control from the Silverlight Controls tab in the Toolbox. By simply dragging and dropping the asp:MediaPlayer control onto a new ASP.NET page and assigning the MediaSource property a valid value, the page is media enabled. However, the ASP.NET Extensions Preview controls, including the asp:MediaPlayer control requires use of the ASP.NET AJAX script library, hence any page that uses the asp:MediaPlayer control must have an asp:ScriptManager control on the page. The markup shown below was created by dropping the asp:MediaPlayer control on a new ASP.NET page and assigning a value to the MediaSource property. Additionally, Microsoft Expression Encoder was used to add chapter positions and thumbnails to the video.

Code Sample: TheSilverlightFramework/Demos/aspMediaPlayer/Default.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<%@ 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">
<head runat="server">
 <title>Untitled Page</title>
 <script type="text/JavaScript">
  function onChapterStarted(sender, chapterEventArgs) {
   var chapter = sender.get_currentChapter();
   Sys.Debug.trace("Chapter Title: " + chapter._title);
  }
 </script>
</head>
<body>
<form id="form1" runat="server">
 <asp:ScriptManager ID="ScriptManager1" runat="server"> </asp:ScriptManager>
 <div>
  <asp:MediaPlayer OnClientChapterStarted="onChapterStarted" MediaSkinSource="~/CustomProfessional.xaml" 
  AutoPlay="true" ID="MediaPlayer2" runat="server" Height="400px" Width="600px" 
  MediaSource="~/SteveBreastonCardinalsPuntReturn.wmv">
   <Chapters>
    <asp:MediaChapter Title="Start" Position="0.0" ThumbnailSource="~/EMEOutput/SteveBreastonCardinalsPuntReturn_0.000.jpg" />
    <asp:MediaChapter Title="Reception" Position="6.6253847" ThumbnailSource="~/EMEOutput/SteveBreastonCardinalsPuntReturn_10.528.jpg" />
    <asp:MediaChapter Title="Broken Tackle" Position="10.5280086" ThumbnailSource="~/EMEOutput/SteveBreastonCardinalsPuntReturn_13.160.jpg" />
    <asp:MediaChapter Title="End Zone" Position="13.1600108" ThumbnailSource="~/EMEOutput/SteveBreastonCardinalsPuntReturn_17.335.jpg" />
    <asp:MediaChapter Title="Replay" Position="17.3349108" ThumbnailSource="~/EMEOutput/SteveBreastonCardinalsPuntReturn_6.625.jpg" />
    <asp:MediaChapter Title="Celebration" Position="55.1768291" ThumbnailSource="~/EMEOutput/SteveBreastonCardinalsPuntReturn_71.246.jpg" />
    <asp:MediaChapter Title="End" Position="71.2455760" ThumbnailSource="~/EMEOutput/SteveBreastonCardinalsPuntReturn_83.498.jpg" />
   </Chapters>
  </asp:MediaPlayer>
 </div>
</form>
</body>
</html>

The same page displayed in Design view shows the Silverlight media player as shown in the figure below:

When run, the ASP.NET page plays the media file targeted by the asp:MediaPlayer control as shown below:

Chapters

Audio and video, and the combination thereof, are generically referred to as media. Media may exist in various formats. Most media vendors, such as Microsoft, Apple, and Real, distribute and save media in proprietary formats and most media players will play media in multiple formats. There are also industry standard media formats that most players also support. Media may be stored in a particular format when it is saved after being recorded or may be converted from one format to another using a converter tool.

When media is prepared for playback in a particular format, the process is referred to as media encoding. During the encoding process, the stream of media bits may also be manipulated and modified. For instance, using a media encoder, a media (video / audio) stream may be played to a certain point and then another media source may be interjected. Television production studios perform this type of encoding action to interject a commercial into a live or recorded media stream (television show) that is being broadcast.

Microsoft released the Expression Encoder (EE) with the Expression Suite of designer tools. Using EE, you can define markers, similar to bookmarks, in a media stream. The asp:MediaPlayer control detects these markers in the media stream and can respond to them. Using the Silverlight player, a user can jump in the media playback from one marker to another. Furthermore, events can automatically be fired when a new marker is encountered. Markers are generally referred to as chapters. EE with imported media with markers defined is shown in the following figure:

When media is prepared and encoded using EE, including markers, the output in Visual Studio 2008 appears as shown in the figure below:

The asp:MediaPlayer control includes functionality for navigating defined markers, or chapters, in encoded media. The asp:MediaPlayer control includes a child element named <Chapters> that is used to define the chapters in encoded media. The <Chapters> element, in turn, contains a series of <asp:MediaChapter> elements that correlate to each chapter in the media. Each <asp:MediaChapter> element may contain three attributes:

  • Title: defines the title of a chapter and is displayed by the media player to identify the chapter.
  • Position: defines location in the encoded media where the chapter begins.
  • ThumbnailSource: identifies an image that is displayed by the media player to visually identify the chapter.

Attribute values can be assigned using the marker definitions in EE. Note that the Position value convertible to a double numeric value, hence some conversion of values from EE to asp:MediaPlayer might be necessary. For instance, in the example shown here, the marker at the end of the media is shown at 1.11.2455760 in EE whereas it must be converted to the actual number of seconds in the Position attribute as 71.2455760. The resulting asp:MediaPlayer element definition is shown in the markup snippet below:

<asp:MediaPlayer AutoPlay="true" ID="MediaPlayer2" runat="server" Height="400px" Width="600px" MediaSource="~/SteveBreastonCardinalsPuntReturn.wmv">
 <Chapters>
  <asp:MediaChapter Title="Start" Position="0.0" ThumbnailSource="~/EMEOutput/SteveBreastonCardinalsPuntReturn_0.000.jpg"/>
  <asp:MediaChapter Title="Reception" Position="6.6253847" ThumbnailSource="~/EMEOutput/SteveBreastonCardinalsPuntReturn_10.528.jpg"/>
  <asp:MediaChapter Title="Broken Tackle" Position="10.5280086" ThumbnailSource="~/EMEOutput/SteveBreastonCardinalsPuntReturn_13.160.jpg"/>
  <asp:MediaChapter Title="End Zone" Position="13.1600108" ThumbnailSource="~/EMEOutput/SteveBreastonCardinalsPuntReturn_17.335.jpg"/>
  <asp:MediaChapter Title="Replay" Position="17.3349108" ThumbnailSource="~/EMEOutput/SteveBreastonCardinalsPuntReturn_6.625.jpg"/>
  <asp:MediaChapter Title="Celebration" Position="55.1768291" ThumbnailSource="~/EMEOutput/SteveBreastonCardinalsPuntReturn_71.246.jpg"/>
  <asp:MediaChapter Title="End" Position="71.2455760" ThumbnailSource="~/EMEOutput/SteveBreastonCardinalsPuntReturn_83.498.jpg"/>
 </Chapters>
</asp:MediaPlayer>

The Silverlight media player is capable of navigating the chapters in the encoded media once the chapters are defined. Tto navigate the chapters, the user hovers the mouse over the bottom of the player and the chapter images will be displayed. By clicking one of the chapter images, the media jumps to that chapter. The resulting player is shown in the following image:

Skins

The asp:MediaPlayer control includes several built-in skins that are used to change the appearance of the media player. The built-in skin can easily be changed using Visual Studio 2008 either declaratively in the markup through intellisense or visually in the designer. A custom skin can also be provided for the media player by creating a custom XAML file and referencing the XAML file through the MediaSkinSource attribute of the asp:MediaPlayer control.

An easier method of creating a custom player skin is to import an existing skin and modify it. To import and modify a skin using Visual Studio 2008, use the asp:MediaPlayer control smart tag menu in design view and select Import Skin. Select the skin to be imported and then click the Import button. The selected skin will be copied to the local project folder. Modify the skin XAML and then select the modified XAML as a the current skin. For example, in the figure below, the Professional skin was imported, modified to add some orange highlights, and then selected as the active skin.

Handling Media Player Events

The Microsoft Silverlight plug-in includes a framework of namespaces, classes, and functionality that are used to interact with the media player and create applications. Classes in the Silverlight documentation are referred to as client types. This makes sense as a class, in object-oriented terminology, is defined as representing a particular type of entity.

The Player type is tightly coupled to the media player. The media player and its active skin are defined using XAML. As such, the XAML used to define the player skin must adhere to a specific XML grammar so that the Player type can assume that particular elements exist within the player skin XAML. If the player skin XAML includes the correct elements, identifying functions to handle player events using the asp:MediaPlayer control is a simple process. Function handlers can easily be identified either declaratively or through the designer using Visual Studio 2008. The full markup of the page with the OnClientChapterStarted function handler defined is shown in the markup listing below:

Code Sample: IntegratingSilverlightWithASPNETAJAX/Demos/aspMediaSimple/Default.aspx

<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>
<%@ Register Assembly="Microsoft.Web.Preview" Namespace="Microsoft.Web.Preview.UI.Controls" 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">
<head runat="server">
 <title>My Cardinals Videos</title>
 <script type="text/JavaScript">
 function onChapterStarted(sender, chapterEventArgs) {
  var chapters = sender.get_chapters();        
  var ci = chapterEventArgs.get_chapterIndex();
  var chapter = chapters[ci];
  
  Sys.Debug.trace("Chapter Info" + chapter.imageUrl + " " + chapter.title);
 }
 </script>
</head>
<body>
<form id="form1" runat="server">
 <asp:ScriptManager ID="smCardinalVideos" runat="server"> </asp:ScriptManager>
 <div>
  <asp:Media ID="myCardVideo" AutoPlay="true" runat="server" Height="388px" MediaUrl="~/EMEOutput/SteveBreastonCardinalsPuntReturn.wmv" 
        Width="512px" XamlUrl="~/CustomProfessional.xaml" OnClientChapterStarted="onChapterStarted">
   <Chapters>
    <asp:MediaChapter Title="Start" TimeIndex="0.0" ImageUrl="~/EMEOutput/SteveBreastonCardinalsPuntReturn_MarkerThumb 00.00.00.jpg" />
    <asp:MediaChapter Title="Reception" TimeIndex="6.6253847" ImageUrl="~/EMEOutput/SteveBreastonCardinalsPuntReturn_MarkerThumb 00.00.06.6253847.jpg" />
    <asp:MediaChapter Title="Broken Tackle" TimeIndex="10.5280086" ImageUrl="~/EMEOutput/SteveBreastonCardinalsPuntReturn_MarkerThumb 00.00.10.5280086.jpg" />
    <asp:MediaChapter Title="End Zone" TimeIndex="13.1600108" ImageUrl="~/EMEOutput/SteveBreastonCardinalsPuntReturn_MarkerThumb 00.00.13.1600108.jpg" />
    <asp:MediaChapter Title="Replay" TimeIndex="17.3349108" ImageUrl="~/EMEOutput/SteveBreastonCardinalsPuntReturn_MarkerThumb 00.00.17.3349108.jpg" />
    <asp:MediaChapter Title="Celebration" TimeIndex="55.1768291" ImageUrl="~/EMEOutput/SteveBreastonCardinalsPuntReturn_MarkerThumb 00.00.55.1768291.jpg" />
    <asp:MediaChapter Title="End" TimeIndex="71.2455760" ImageUrl="~/EMEOutput/SteveBreastonCardinalsPuntReturn_MarkerThumb 00.01.11.2455760.jpg" />
   </Chapters>
  </asp:Media>
 </div>
</form>
</body>
</html>

The resulting Visual Studio 2008 Output window is shown in the figure below.

Creating a Silverlight Application

Now that we have a basic understanding of some of the aspects of a Silverlight application, we should get started by building a sample Silverlight application.

The Silverlight Project

The first thing to do when creating a Silverlight application in Visual Studio is to create a new project. The fantasy picks application will be created using Silverlight 2 and C#. The New Project dialog is shown in the figure below.

Immediately after clicking OK to instruct Visual Studio 2008 to create the new Silverlight project, Visual Studio will prompt for additional information. Visual Studio configures a Silverlight application for testing on the server when the application is created. A Silverlight application is considered a control that will always be hosted in some type of Web page. The options offered by Visual Studio are displayed in the Add Silverlight Application dialog shown below:

As shown above, the available options are to:

  • Add a new ASP.NET Web to the solution to host Silverlight: This is the most commonly selected option and will create an ASP.NET Web project in addition to the Silverlight project. The ASP.NET Web project will be used to test the Silverlight application.
  • Automatically generate a test page to host Silverlight at build time: This option should be used to manually create a Web page for testing the Silverlight application, most likely in scenarios where the test page will be created in a technology other than ASP.NET, such as PHP.
  • Link this Silverlight control into an existing Web site: This option is used to link the new Silverlight project to an existing ASP.NET test project.

Other options on the Add Silverlight Application dialog are available conditionally based on the option selected at the top of the dialog. The Project Type dropdown offers options to create an ASP.NET Web Site or an ASP.NET Web Application Project. Finally, the Name textbox offers the option to change the default name of the newly created Web Site (which we have done).

When the new project is created, two projects will appear in the Solution Explorer as shown in the figure below:

In the figure above, the first project shown is the Web Site and will serve as the test harness. The second project shown is the Silverlight application. In the Silverlight application, the only files really of interest at this time will be the Page.xaml file and the associated code behind file, Page.xaml.cs. Visual Studio automatically opens Page.xaml for editing. In Visual Studio 2008, Silverlight 2 applications must be hand-coded in XAML. The designer is only for viewing the results.

Walkthrough of Expression Blend

An alternative to using Visual Studio to create XAML is to design XAML using Expression Blend. A Silverlight application created in Visual Studio can easily be opened in Expression Blend by right-clicking on the Page.xaml file in the Visual Studio Solution Explorer and selecting Open in Expression Blend from the context menu. When opening a Silverlight XAML file in Expression Blend from Visual Studio, Expression Blend may prompt with the dialog shown below as a security precaution:

Given that the Page.xaml file was intentionally opened from Visual Studio 2008, it is safe to select Yes from the dialog. The Page.xaml file will then be displayed by Expression Blend as shown below:

Notice that Expression Blend displays the same projects and files in the Solution Explorer as Visual Studio 2008. A new Silverlight project could, alternatively, be created from within Expression Blend. The Expression Blend New Project dialog is shown below. When a new Silverlight application is created from within Expression Blend, no test harness Web application is created. Hence, it is typically preferred to create a new Silverlight application using Visual Studio 2008 and then design it using Expression Blend.

The Design Surface

The central workspace in Blend is the design surface, where controls are drawn out and translated into XAML. We can choose to view the XAML by using the XAML View Tab at the right side of the design surface. Blend also provides a "Split" view which allows us to see both the visual design and XAML view at the same time. Split view is very handy when you are beginning to learn XAML, as you can immediately correlate XAML syntax to its resulting User Interface.

The Toolbox

At the left side of the Blend interface are icons for all of the controls available to us. All controls in the toolbox provide a tooltip (accessible when hovering over the button with the mouse), and a hotkey (which is shown in the tooltip). A hotkey is a key you can press to quickly activate that control in the toolbox. Let's perform a walkthrough of the toolbox so we can gain some familiarity with each control.

Shape Primitives

Probably the simplest controls in the toolbox are the Shape primitives, located near the bottom of the toolbox. Note that some buttons in the Toolbox actually contain more than one control. These buttons are denoted with a small white arrow at their bottom left corner. In this case, the Shape button shows a Rectangle by default - but if you click and hold the mouse button on the Rectangle box, you will see a flyout window appear which contains Rectangle, Ellipse, and Line shape primitives:

To draw a shape, select either the Rectangle, Ellipse, or Line control in the Toolbox and then draw out the shape on the Design Surface.

Drawing Tools (Pen and Pencil)

The Pen and Pencil tools allow for the creation of XAML Path elements. A Path element is a collection of points which makes up a custom shape. The Pen tool allows the user to click the mouse for each point in the drawing, which is useful for more controlled drawing of complex shapes, while the Pencil tool allows for freehand drawing.

Try drawing out some shapes with the Pen tool. When you place a point, you can optionally click and drag the mouse to create a Bezier curve. To complete and close the shape, you can click on the first point that you used to begin drawing the shape.

Select and Direct Select Tools

After drawing a shape, you may want to later modify its position, rotation, or other properties. We can select a shape for modification using the Select and Direct Selection tools. The Select tool allows you to select and rotate an entire shape, while the Direct Select tool allows you to modify individual points that make up a Path.

Try drawing out a Path with the Pen tool. Then use the Select tool to click on the Path. Note that several handles appear around the shape, which you can click and drag to modify the shape. The handles at the corners of the shape are Rotate Handles, and change the angle of rotation. There are also Scale Handles at the sides of the shape, which can be used to skew the height or width of the shape. At the center of the shape is a Rotation Point handle, which will modify the center of rotation for the shape. Try dragging the Rotation Point to a different location and see how it affects the rotation behavior when using a Rotate handle:

Pan and Zoom Tools

The Design Surface in Blend can be scrolled using the Horizontal and Vertical Scrollbars. You can also pan (scroll the viewing area) using the Pan Tool from the toolbox. The Pan Tool resembles a hand and, when selected, allows you to click and drag the viewing area around. You can also double-click the Pan Tool Icon to center all content on the design surface. The Zoom Tool allows you to zoom in and out of the design surface. After selecting the Zoom Tool, click on the design surface to zoom in, and press Alt and click to zoom out. You can also double-click the Zoom tool to zoom the design view to it's largest extents.

Brush Properties and Brush Tools

Brushes define the color of shapes, including fill color, outline color ("stroke"), and texture. We use the Brushes Panel in the Properties Window to define brushes for a shape. The Brushes Panel includes three Brush Options:

  1. No Brush clears any previously applied brush information.
  2. Solid Color Brush creates a brush with a solid fill color.
  3. Gradient Brush creates a linear gradient or radial gradient, with two or more "gradient stops."

We can also create Brush Resources using the Convert Brush to Resource tool. By creating and using Brush Resources, we can quickly make color changes that affect the entire design. For example, let's suppose we have a lot of elements that share a similar Red color scheme. But later on, a decision is made to change the Red color scheme to Green. By sharing Brush Resources, we can make the color changes in just one spot, instead of having to modify every object with that color.

Gradient Brushes are composed of two or more colors that are blended together. To define a Gradient Brush, we first go to the Gradient Brush Panel and select either a Linear Gradient or Radial Gradient fill. Then, we can add Gradient Stops and set their color. To add a Gradient Stop, just click anywhere in the Gradient Stop slider. To remove a Gradient Stop, click and drag the stop down off the slider.

Layout Tools

Silverlight contains several layout controls, or controls that can contain other child controls within their borders. These controls are available in the Toolbox under the Layout controls subpanel, and are discussed further in The Silverlight Controls chapter.

Input controls

Silverlight contains input controls for Line of Business type applications. Blend provides these controls under the Text, Input, and Asset Library Toolbox Icons. We'll discuss these controls further in the Silverlight Controls chapter of the course.

Brushes and Brush Tools

We can apply Brushes to either the Fill (inside color) of a shape, Stroke (border color) of a shape, or the Opacity Mask (Transparency of a shape). To select where we want to apply a Brush, we use the Fill, Stroke, and OpacityMask selection tools:

Now that we have a familiarity with the different brush types, let's revisit the Brush Tools available in the Toolbox, which allow us to manipulate brushes on a shape:

The Eyedropper tool allows you to copy the brush information from one object to another. To use the Eyedropper, first use the Select tool to highlight the object you wish to apply a copied brush to. Then use the Eyedropper to click on the object containing the brush you want to copy.

The Paint Bucket tool works like the Eyedropper, but in reverse. To use the Paint Bucket, first use the Select tool to highlight the object containing the Brush you wish to copy. Then select the Paint Bucket tool and click the object you want to copy the brush to.

The Brush Transform tool allows you to manipulate the position of Gradient Brush patterns on an object. You can modify the X,Y offset of the gradient as well as the angle. Try applying a gradient brush to an object and then use the Brush Transform tool to move (by dragging) the gradient around, and rotate (by clicking and dragging the rotate handles) the gradient.

Objects and Timeline Panel

The Objects and Timeline Panel is used to select objects on the Design Surface, and to define animation using StoryBoards. We'll look at animation in just a bit, but for now let's look at how the Objects and Timeline window can be used to select and manipulate objects:

  • You can click and drag items in the Objects list to change their front-to-back order on the screen, or place them into different layout containers.
  • You can rename objects by clicking the object name in the Objects list and entering a new name.
  • You can right-click objects in the Objects list to view the standard context menu for that object.
  • You can hide objects temporarily using the Hide/Show icon.
  • You can lock objects in place using the Lock/Unlock icon.

Properties and Events Tab

As we learned previously, the Properties Tab allows us to view and edit attributes on objects such as Brushes. It also dynamically changes to show specific attributes for each object type. For example, a TextBlock object will expose its Text property in the Properties Window.

Blend also allows us to view the Events generated by each object type. To view the events, select the Events icon on the Properties page:

We can then double-click any row in the Events list and Blend will communicate with Visual Studio to create an Event Handler in code. This allows us to write code inside Visual Studio to be executed when that event is triggered.

Grouping and Combining Objects

Often, a user interface requires shapes that are composed of multiple primitive shapes combined into a new shape. Also, you may need to Group objects into a single container so that you can manipulate (move, scale, rotate, etc.) all objects in the container as a single unit. Blend fully supports both Combining and Grouping, as we'll learn below.

Grouping Objects

We can group objects into a single container using the Object/Group Into submenu. This is handy for instances where a logical UI Element is composed of multiple shapes. For example, perhaps you have a logo that is made up of several Paths. By grouping all of the Paths into a single Canvas, we can move, scale, and rotate the entire logo in one operation. Additionally, we could assign the Canvas a name and manipulate the entire logo through code. The "Group Into" menu option allows you to group items into any Layout container type (we'll look more at layout container types in the Silverlight Controls chapter).

Combining Objects using Operators

Blend has the ability to combine shapes into a single object using logical operators, which are available under the "Object/Combine" menu option. These operators allow you to Unite, Divide, Intersect, Subtract, and Exclude Overlap. Simply use the Select tool to highlight two shapes that you wish to logically combine, and select the appropriate function from the Object/Combine submenu.

Designing the XAML

Now that we have a familiarity with Expression Blend, our goal is to create a basic version of the fantasy picks page used in previous modules. The fantasy picks page is shown in the figure below.

To get started, in Visual Studio 2008, right-click the Page.xaml file in the Solution Explorer and select Open in Expression Blend.

Next, we need to set the background of the page. Use the Brushes subpanel of the Properties panel to configure the background as shown in the figure below.

Bear in mind that we are now working in client-side code in our code behind file. With the code behind file being written in a traditionally server-side language, it's easy to forget that the code contained therein will execute on the client. As such, if a Silverlight application must display data from a server-side data source, it must connect to that data source over the Web. The easiest method for retrieving data over the Web will be to use a Web service. We'll cover Silverlight using Web services in a later chapter. For now, to make life easy on ourselves, the button click event will display a literal string value. The completed XAML formatting in Expression Blend is shown below:

Note that if you have a document open in Visual Studio or Expression Blend and modify the document externally, when you return to the open document, both Visual Studio and Expression Blend will detect the external modification and prompt to reload a fresh copy of the document as stated in the dialog below:

Wiring Up the Button

We haven't discussed the details of writing code in a Silverlight environment yet, hence we'll display a string literal on this sample for the time being. In order to create an event handler for the button:

  • In Visual Studio: The Cider designer is still in a read-only mode as of Silverlight 2, hence the options for creating an event handler in Visual Studio are to create the event handler manually in the code behind file and then associate the event handler with the target control. Additionally, from the XAML editor, if an event is selected from the Intellisense dropdown for a particular control, Visual Studio displays a list of all existing event handlers and an option to create a new event handler.
  • In Expression Blend: Select the control (in this case, the button) to create an event handler for and then select the event to create a handler for from the Events page on the Properties window. Expression Blend does not include a code editor so Blend will open up the event handler in Visual Studio for completion. To create the event handler, double-click the event name in the events list.

Complete the event handler and test the application in Visual Studio. The resulting application is shown below as displayed in Safari. If prompted to enable debugging, select the option to do so.

The XAML that was used to create the Silverlight form in the figure above is shown in the listing below.

Code Sample: TheSilverlightFramework/Demos/myFantasyPicksSL/myFantasyPicksSL/Page.xaml

<UserControl x:Class="myFantasyPicksSL.Page"
    xmlns="http://schemas.microsoft.com/client/2007" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    Width="400" Height="195">
    <Grid x:Name="LayoutRoot" Height="195">
     <Grid.Background>
      <LinearGradientBrush EndPoint="0.105999998748302,0.218999996781349" StartPoint="0.920000016689301,0.907999992370605">
       <GradientStop Color="#FF172E0A"/>
       <GradientStop Color="#FF16586F" Offset="1"/>
       <GradientStop Color="#FFD8ECEE" Offset="0.49300000071525574"/>
       <GradientStop Color="#FF9E9062" Offset="0.27599999308586121"/>
      </LinearGradientBrush>
     </Grid.Background>
     <TextBlock Height="30" Margin="8,8,18,0" VerticalAlignment="Top" TextWrapping="Wrap">
      <Run FontFamily="Portable User Interface" FontSize="16" FontStretch="Normal" FontStyle="Normal" FontWeight="Bold" Foreground="#FFF1E39B" Text="Welcome to the Fantasy Manager"/>
     </TextBlock>
     <Path Height="1" HorizontalAlignment="Stretch" Margin="10,34,16,0" VerticalAlignment="Top" Data="M10,34 L383,34" Fill="#FFF1E39B" Stretch="Fill" Stroke="#FFF1E39B"/>
     <Path HorizontalAlignment="Stretch" Margin="10,0,16,31" VerticalAlignment="Bottom" Data="M10,34 L383,34" Fill="#FF704B0B" Stretch="Fill" Stroke="#FFC4B04C" Height="1" OpacityMask="#FF704B0B"/>
     <TextBlock Height="30" Margin="8,167,18,0" VerticalAlignment="Top" TextWrapping="Wrap" OpacityMask="#FF704B0B" Foreground="#FFA79229">
      <Run FontFamily="Portable User Interface" FontSize="10" FontStretch="Normal" FontStyle="Normal" FontWeight="Normal" Foreground="#FFC4B04C" Text="copyright 2008 - the fantasy league manager"/>
     </TextBlock>
     <TextBlock Margin="10,87,18,41" TextWrapping="Wrap" x:Name="tbResults">
      <Run FontFamily="Portable User Interface" FontSize="14" FontStretch="Normal" FontStyle="Normal" FontWeight="Normal" Foreground="#FF5BAEDF"  />
     </TextBlock>
     <Path Height="1" HorizontalAlignment="Stretch" Margin="10,71,16,0" VerticalAlignment="Top" Data="M10,34 L383,34" Fill="#FFF1E39B" Stretch="Fill" Stroke="#FFF1E39B"/>
     <Button Height="23" HorizontalAlignment="Stretch" Margin="10,42,181,0" VerticalAlignment="Top" Content="Display My Fantasy Picks" Background="#FFC2810D" Click="Button_Click" x:Name="myButton" />

    </Grid>
</UserControl>

The click event handler that handles the button click is shown in the code snippet below.

Code Sample: TheSilverlightFramework/Demos/myFantasyPicksSL/myFantasyPicksSL/Page.xaml.cs

using System;
using System.Collections.Generic;
using System.Linq;
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 myFantasyPicksSL
 {
 public partial class Page:UserControl
  {
  public Page ( )
   {
   InitializeComponent();
   }

  private void Button_Click (object sender, RoutedEventArgs e)
   {
   tbResults.Text = "My picks for the week are .... ";
   }
  }
 }

Silverlight Project Architecture

As mentioned previously, when a new Silverlight project is created using Visual Studio, two projects are created. One project is the project that contains the actual Silverlight application and the second project serves as a test harness for the Silverlight application. When a Silverlight project is created by using Expression Blend, only the Silverlight project is created and not the test harness project.

A Silverlight project may contain multiple Silverlight files. Each Silverlight file is built upon the same architecture as ASP.NET and many other Microsoft .NET development technologies. A Silverlight control is comprised of a file containing XAML and a second file containing code, or code behind files (C#, in this case). Regardless of which tool is used to create a Silverlight project, when the Silverlight application is built, the code behind files are compiled into an assembly (a .dll file) and all of the XAML files and the assembly are compressed into a single file with a .xap extension (pronounced "zap"). The XAP file is the file that will be deployed to the hosting Web server. The project architecture described is illustrated in the figure below.

Notice that in the test harness project, there are three Web pages created, by default. The Default.aspx page is not used in the test harness project. However, there is an ASP.NET page and an HTML page created that are named after the project. The HTML page includes the Silverlight control using an <object> element while the ASP.NET page includes the Silverlight control using a new <asp:Silverlight> element.

Interacting with HTML Pages

In many instances, you may wish to add Silverlight to an existing web application, to enhance (but not entirely replace) the application. In cases such as these, you may want your existing HTML pages to interact with the new Silverlight application. Silverlight provides several ways to do this.

NOTE: For a working example of the techniques below, please refer to the demo application in \ClassFiles\TheSilverlightFramework\Demos\InteractingWithHTML

Interacting with the DOM

The Document Object Model (DOM) is an HTML technology which allows programs to access and modify contents of an HTML page at runtime. Usually, JavaScript is used to access the DOM, but we can also use Silverlight.

Let's assume you have an HTML page with the following DIV inside it:

<div id="myDIV"  style="background:blue;width:20%;height:20%"> 
    </div> 

Inside a Silverlight application on that same page, you could modify the div attributes using the HtmlDocument and HtmlElement classes (part of the System.Windows.Browser namespace) in Silverlight:

 HtmlDocument doc = HtmlPage.Document;    
 HtmlElement div = doc.GetElementById("myDIV");    
 div.SetStyleAttribute("background", "green");

Calling Silverlight from JavaScript

Silverlight code can be called from JavaScript by adding the ScriptableType and ScriptableMember attributes to your code. But you must first call RegisterScriptableObject and give your Silverlight control an alias. The example below exposes the Page class and a method using these attributes:

   [ScriptableType]
    public partial class Page : UserControl
    {
        [ScriptableMember]
        public event EventHandler DoSomething;

        public Page()
        {
            InitializeComponent();
            HtmlPage.RegisterScriptableObject("MySilverlightApp", this);
        }

        [ScriptableMember]
        public void DoSomethingSilverlight()
        {
            System.Windows.Browser.HtmlPage.Window.Alert("JavaScript called DoSomethingSilverlight");
        }

After this Silverlight code is in place, you can call the Silverlight method from JavaScript as follows:

        function callSilverlight() {
            document.getElementById("silverlightPlugIn").content.MySilverlightApp.DoSomethingSilverlight();
        }

Calling JavaScript from Silverlight

You may have JavaScript functions that update HTML elements or do other functionality. We can call these from Silverlight by following a few steps:

  1. Let's assume we have a JavaScript function in the page as follows:
      function HandleDoSomething()
      {
     alert("Silverlight called HandleDoSomething");
      }
  2. First add a [ScriptableType] attribute to the Silverlight Page class and a [ScriptableMember] attribute to a new Event on the Page class: (the event will be raised to notify the HTML page to run the function)
    [ScriptableType]
        public partial class Page : UserControl
        {
            [ScriptableMember]
            public event EventHandler DoSomething;
    
  3. In the Page Constructor, register this page as scriptable:
    HtmlPage.RegisterScriptableObject("MySilverlightApp", this);
  4. Handle the onLoad event in JavaScript, which is fired by the Silverlight plug-in on creation (also assign an ID to the object tag):
      <object id="silverlightPlugIn" data="data:application/x-silverlight-2," type="application/x-silverlight-2" width="100%" height="100%">
       <param name="source" value="ClientBin/InteractingWithHTML.xap"/>
       <param name="onerror" value="onSilverlightError" />
       <param name="onLoad" value="onLoaded" />
       <param name="background" value="white" />
       <param name="minRuntimeVersion" value="2.0.31005.0" />
       <param name="autoUpgrade" value="true" />
       <a href="http://go.microsoft.com/fwlink/?LinkID=124807" style="text-decoration: none;">
            <img src="http://go.microsoft.com/fwlink/?LinkId=108181" alt="Get Microsoft Silverlight" style="border-style: none"/>
       </a>
      </object>
    
  5. Create an OnLoaded event handler in Javascript to wire up the handler in js:
              function OnLoaded(sender, args) {
                document.getElementById("silverlightPlugIn").content.MySilverlightApp.DoSomething = HandleDoSomething;
            }    
    

Silverlight Font Support

Silverlight supports a collection of common fonts out of the box. These fonts are Arial, Arial Black, Comic Sans, Courier New, Georgia, Lucida Grande, Times New Roman, Trebuchet, and Verdana, as shown in the image below:

So what if an application requires another font? Silverlight also supports custom fonts, and the steps to use a custom font are as follows:

  1. Add the font file (.ttf) into your Silverlight Project by selecting Project/Add Existing Item.
  2. Set the Build Action of the .ttf file to Resource
  3. Note the Font Name (the embedded name in the font file). If you are not sure what this is, double-click the .ttf file in Windows Explorer and the Font Name will be displayed at the top of the Font Viewer.
  4. Inside your XAML element (TextBlock, TextBox, etc), set the FontFamily in the format "FontFile#FontName" - For example, to set to a Font named Times Square inside a font file named TIMES_SQ.TTF, you would use:
    <TextBlock FontFamily="TIMES_SQ.TTF#Times Square" FontSize="32" TextWrapping="Wrap" Text="This TextBlock is using a Custom, Embedded Font." />
    -

Silverlight Full Screen Support

Silverlight applications can display in two different modes. In Embedded Mode, the Silverlight application displays within the content area of a web page. In Full-Screen Mode, the Silverlight application occupies the entire screen and displays on top of all other running applications.

To switch modes, we simply set the Content.IsFullScreen property in the System.Windows.Interop namespace. For example, the following line sets the Silverlight application to full screen mode:

Content.IsFullScreen = true;

Security Restrictions

When switching to full screen mode, there are some security restrictions put into place. First, Silverlight will notify the user that the application has gone full screen, and note the Source URL. This notification will look like the following:

The reason for this message is so that a malicious Silverlight developer could not spoof another site, such as a banking site, and trick the user into entering private information such as passwords, etc. Furthermore, in full screen mode, the available input keys are restricted for keyboard input. The only keys that work when in full screen mode are: UP ARROW, DOWN ARROW, LEFT ARROW, RIGHT ARROW, SPACEBAR, TAB, PAGE UP, PAGE DOWN, HOME, END, ENTER

Creating a Silverlight Animation

Creating animations for Silverlight can be a simple process, depending on the animation in mind. The tool to use for creating animation is Expression Blend. Let's create a simple spinning circle (reminiscent of the one displayed in Windows Vista when waiting on a lengthy process to complete) animation and display it in a Silverlight application. Start by creating a new Silverlight application in Visual Studio 2008.

Once created, open the solution for the application just created inside of Expression Blend. You can easily open a Visual Studio 2008 solution in Expression Blend by right-clicking a .xaml file in the Visual Studio 2008 Solution Explorer and selecting the option to open it in Expression Blend. When you open a new solution in Expression Blend, you will be presented with a blank slate to work with.

To create the spinning animation, drag an ellipse from the toolbar onto the XAML design area. With the ellipse selected, use the Properties sheet to configure the ellipse similar to that shown in the figure below.

On the Objects and Timeline pane, select the Open, Create, or Manage Storyboards button. Click the add (+) button to create a new timeline. The Create Storyboard dialog should be presented as shown in the following figure.

Assign the new timeline a name and click OK. Next, select a point on the timeline and modify the ellipse in some manner. In this example, we want to grab the corner anchor of the ellipse using the mouse and spin the ellipse around several times. You can test the animation by clicking the Play button on the timeline pane.

If you want the animation to loop forever, in Expression Blend, select the timeline and in the Properties sheet, set the RepeatBehavior to "Forever". You can save the page and go back to Visual Studio 2008.

In Visual Studio, if you run the Silverlight application as it exists right out of Expression Blend, the animation may appear but won't play. To get the animation to play, you must call the Begin method of the StoryBoard. In order to be able to call the Begin method of the StoryBoard, the StoryBoard must have a name assigned to it. Once the StoryBoard has a name, you can call the Begin method from the Silverlight code behind file as shown in the code snippet below.

public void Page_Loaded(object o, EventArgs e)
{ 
 // Required to initialize variables
 InitializeComponent();
 Spin.Begin();
}

The resulting animated Silverlight page is shown in the figure below.

LAB: Create a Simple Silverlight Application

In this lab, you will create a random quote display using Silverlight. The tool will include an animation and will store exam data in an array (for the time being). The lab includes two exercises.

Exercise: Experiment with a Silverlight Animation

Duration: 10 to 20 minutes.

In this first exercise of the lab, you will use Visual Studio 2008 and Expression Blend to create a simple animation and display it in a Silverlight application.

  1. Start or open Visual Studio 2008.
  2. Create a new Silverlight project.
    1. Select New Project from the File menu.
    2. When prompted with the New Project dialog, select Silverlight Application from the Silverlight node under your language of choice.
    3. Assign the project a name (e.g, SpinAnimation) and location and click OK.
    4. Leave the options in the Add Silverlight Application dialog unchanged and click OK.
  3. Right-click the Page.xaml file in the Visual Studio 2008 Solution Explorer and select Open in Expression Blend.
  4. In Expression Blend, modify the background color of the Silverlight canvas:
    1. In the Objects and Timeline subpanel of the Interaction panel, click LayoutRoot. This makes it possible to change the grid properties.
    2. Using the Brushes subpanel on the Properties panel, modify the background color:
      1. Click on the Background brush.
      2. Click on the Gradient Brush button.
      3. You can set the color for each stop on the color bar. There are already stops at the beginning and end. Click the color bar to add additional stops if you wish.
  5. Highlight the Ellipse (you may have to click on the white triangle on the bottom left of the Rectangle) in the Asset Library and draw an ellipse on the top left corner of the canvas by clicking and dragging your mouse.
  6. With the ellipse selected, using the Brushes subpanel of the Properties panel, select the option to format the Fill and then select the No Brush tab to make the ellipse transparent.
  7. Next, select the Stroke option and in the Appearance category, set the StrokeThickness to 10.
  8. In the Brushes subpanel, select the Gradient Brush tab and configure the gradient for the stroke of the ellipse.
  9. From the Objects and Timeline subpanel, select the Open, create, or manage Storyboards button. Click the add button (+) to create a new timeline. Name the new timeline Spin and click OK.
  10. In the timeline pane, select the 2 second marker.
  11. Move the mouse over the corner of the ellipse on the canvas until the rotation marker is displayed. Spin the ellipse several times.
  12. Click the Play button in the timeline pane to test the animation.
  13. At the top of the canvas editor, click the red circle to turn timeline recording off.
  14. Select the Spin timeline in the Objects and Timeline subpanel and, in the Properties panel, change the RepeatBehavior to "Forever".
  15. Add a TextBlock to the canvas next to the ellipse. Change the text to "My First Silverlight Animation" or something similar.
  16. Save the application in Expression Blend and switch back to Visual Studio 2008. When prompted to reload the file in Visual Studio 2008, select Yes.
  17. Press F5 to test the application. Notice that the animation does not function. Close the browser.
  18. In the Visual Studio 2008 XAML editor, place the cursor in the <UserControl> document element and press the space bar. Intellisense should appear. Choose the Loaded event and select New Event Handler from the menu provided.
  19. In the code behind file, in the newly created event handler, enter the code Spin.Begin();.
  20. Press F5 to test the application. The animation should now function.

Exercise: Create Sample Quote Application

Duration: 20 to 45 minutes.

In this exercise, you will create a sample application that displays random quotes.

  1. In Visual Studio 2008, create a new Silverlight application by selecting New Project from the File menu. When prompted with the New Project dialog, select Silverlight Project from the Silverlight node under your language of choice. Assign the project a name and location and click OK.
  2. Right-click the Page.xaml file in the Visual Studio 2008 Solution Explorer and select Open in Expression Blend.
  3. In Expression Blend, modify the background color of the Silverlight canvas using the Brushes category on the Properties sheet.
  4. Drop a StackPanel control onto the design area and adjust it to be the same size as the canvas. Ensure that the Orientation property of the StackPanel is set to Vertical.
  5. Drop a TextBlock control onto the StackPanel control. The TextBlock should automatically size itself and position itself at the top left corner of the canvas. Change the Text property to something similar to "Daily Quote". Adjust the font to appear as a header for the control. Adjust the TextBlock Padding properties to something close to 10.
  6. Drop another StackPanel control onto the canvas. Adjust the Orientation property to Horizontal.
  7. Drop another TextBlock onto the second StackPanel and adjust the Font and Text properties. Set the Text property to something similar to "Relax and consider this...". Adjust the TextBlock Padding properties to something close to 8.
  8. Drop a Button control onto the second StackPanel. The Button should position itself after the second TextBlock. Adjust the Button Content property to something similar to "Get A Quote". Adjust the Button Background property to look nice with the canvas and design. Adjust the Button Name property to something similar to btnGetQuote.
  9. Drop another TextBlock control onto the first StackPanel below the second StackPanel. Adjust the TextBlock font size and color according to your canvas design. Adjust the TextBlock Text property to an empty string. Adjust the TextBlock Name property to something similar to tbQuote. Adjust the TextBlock Padding properties to something close to 8.
  10. Save all changes made in Expression Blend.
  11. Close Expression Blend and switch back to Visual Studio 2008.
  12. In the XAML editor, add a new event handler to the btnGetQuote button.
  13. Right-click the Page.xaml file in the Solution Explorer and select View Code to open the code behind file.
  14. We need to create an event handler in this file to handle the Click event of the button in the XAML. The event handler should store random quotes in an array and pull them randomly to display them in the tbQuote TextBlock. Attempt to write this on your own. When you are done, the end result should resemble the code snippet below (except that some actual quote should be in the array elements such as "Roses are red...").
    protected void GetAQuote(object sender, EventArgs e) {
     string[] quotes = new string[10];
     quotes[0] = "1";
     quotes[1] = "2";
     quotes[2] = "3";
     quotes[3] = "4";
     quotes[4] = "5";
     quotes[5] = "6";
     quotes[6] = "7";
     quotes[7] = "8";
     quotes[8] = "9";
     quotes[9] = "10";
     Random rand = new Random();
     tbQuote.Text = quotes[rand.Next(9)];
    }
  15. The resulting Silverlight application should resemble the following figure.

The Silverlight Framework Conclusion

In this lesson of the Silverlight tutorial, you

  • Studied an overview of Silverlight applications and tools
  • Reviewed creating a Silverlight application
  • Explored creating a Silverlight animation

Footnotes

  1. To learn more about IronPython, visit the IronPython home page on CodePlex located at http://www.codeplex.com/Wiki/View.aspx?ProjectName=IronPython. The download contains a tutorial on using IronPython. Additionally, the following link contains very useful examples and information http://www.codeplex.com/IronPython/Wiki/View.aspx?title=Differences&referringTitle=Home.

  2. To learn more about IronRuby, visit the IronRuby home page located at http://www.ironruby.net/.

  3. In beta at the time of this writing.

To continue to learn Silverlight go to the top of this page and click on the next lesson in this Silverlight Tutorial's Table of Contents.
Last updated on 2009-05-19

Use of http://www.learn-silverlight-tutorial.com (Website) implies agreement to the following:

Copyright Information

All pages and graphics on Website are the property of Webucator, Inc. unless otherwise specified.

None of the content on Website may be redistributed or reproduced in any way, shape, or form without written permission from Webucator, Inc.

No Printing or saving of pages or content on Website

This content may not be printed or saved. It is for online use only.


Linking to Website

You may link to any of the pages on Website; however, you may not include the content in a frame or iframe without written permission from Webucator, Inc.


Warranties

Website is provided without warranty of any kind. There are no guarantees that use of the site will not be subject to interruptions. All direct or indirect risk related to use of the site is borne entirely by the user. All code and explanations provided on this site are provided without warranties to correctness, performance, fitness, merchantability, and/or any other warranty (whether expressed or implied).


For individual private use only

You agree not to use this online manual to deliver or receive training. If you are delivering or attending a class that is making use of this online manual, you are in violation of our terms of service. Please report any abuse to courseware@webucator.com. If you would like to deliver or receive training using this manual, please fill out the form at http://www.webucator.com/Contact.cfm