Microsoft Silverlight
Microsoft Silverlight
Microsoft Silverlight
Introducing SECOND
Microsoft
EDITION
®
Silverlight 2 ™
Laurence Moroney
Chapter 1
Introducing Silverlight 2
Silverlight represents the next step toward enriching the user’s experience through the tech-
nology of the Web. The goal of Silverlight is to bring the same fidelity and quality found in
the user interfaces (UIs) associated with desktop applications to Web applications, allowing
Web developers and designers to build applications for their clients’ specific needs. It is de-
signed to bridge the technology gap between designers and developers by giving them a
common format in which to work. This format will be rendered by the browser and will be
based on XML, making it easy to template and to generate automatically. The format is
XAML—Extensible Application Markup Language.
Before XAML, a Web experience designer would use one set of tools to express a design using
familiar technology. The developer would then take what the designer provided and would
interpret it using the technology of his or her choice. The design would not necessarily trans-
fer properly or problem-free into development, and the developer would need to make many
alterations that could compromise the design. With Silverlight, the designer can use tools that
express a design as XAML, and the developer can pick up this XAML, activate it with code, and
deploy it.
The first part of this book will introduce you to the fundamentals of Silverlight 2 by looking at
the design and development tools that are available to you, and the second part will examine
the programming model more closely.
x Mobile devices
x Digital home products
3
4 Part I Introducing Silverlight 2
However, as these platforms are converging, the user’s expectations are also increasing—and
the term rich is now commonly used to describe an experience above the current baseline
level of expectation. For example, the term “rich Internet application” was coined in response
to the increased level of sophistication that Web users were seeing in applications powered by
AJAX to provide a more dynamic experience in scenarios, such as e-mail and mapping. This
evolution in expectations has led to customers who now demand ever richer experiences that
not only meet the needs of the application in terms of functionality and effectiveness but also
address the perception of satisfaction that the user has with a company’s products and ser-
vices. This can lead to a lasting relationship between the user and the company.
As a result, Microsoft has committed to the User Experience (UX) and is shipping the tools and
technologies that you as a developer can use to implement rich UX applications. Additionally,
they are designed to be coherent—that is, skills in developing UX-focused applications will
transfer across the domains of desktop and Web application development. So, if you are build-
ing a rich desktop application but need a Web version, then you will have a lot of cross-
pollination between the two. Similarly, if you are building a mobile application and need an In-
ternet version, you won’t need two sets of skills, two sets of tools, and two sets of developers.
Concentrating on the Web, Figure 1-1 shows the presentation and programming models that
are available today. As you can see, the typical browser-based development technologies are
CSS/DHTML in the presentation model and JavaScript/AJAX/ASP.NET in the development
model. On the desktop, with the .NET Framework 3.x, XAML provides the presentation model,
and the framework itself provides the development model. There is an overlap between these,
and this is where the Silverlight-enhanced browser provides a “best of both worlds” approach.
Chapter 1 Introducing Silverlight 2 5
Presentation
Model CSS/DHTML
XAML
Programming
JavaScript/AJAX/ASP.NET
Model
.NETFramework
The typical rich interactive application is based on technologies that exist in the unenhanced
browser category. The typical desktop application is at the other end of the spectrum, using
unrelated technologies. The opportunity to bring these together into a rich application that is
lightweight and runs in the browser is realized through the Silverlight-enhanced browser that
provides the CSS/DHTML and XAML design model and the JavaScript/AJAX/.NET Framework
programming model.
Silverlight achieves this by providing a browser plug-in that enhances the functionality of the
browser with the typical technologies that provide rich UIs, such as timeline-based animation,
vector graphics, and audiovisual media. These are enabled by the Silverlight browser-based
XAML rendering engine. The rich UI may be designed as XAML, and because XAML is an
XML-based language and because XML is just text, the application is firewall-compatible and
(potentially) search-engine friendly. The browser receives the XAML and renders it.
When combined with technology such as AJAX and JavaScript, this can be a dynamic proc-
ess—you can download snippets of XAML and add them into your UI, or you can edit, rear-
range, or remove XAML that is currently in the render tree using simple JavaScript
programming.
Silverlight Architecture
As I mentioned, the core functionality of Silverlight is provided by a browser plug-in that ren-
ders XAML and provides a programming model that can be either JavaScript and browser-
based or the .NET Framework and CLR-based. The architecture that supports this is shown in
Figure 1-2. When scripting the control in the browser, the main programming interface that is
exposed in Silverlight 1.0 is via the JavaScript DOM API. This allows you to catch user events
that are raised within the application (such as mouse moves or clicks over a specific element)
6 Part I Introducing Silverlight 2
and have code to execute in response to them. You can call methods on the JavaScript DOM
for XAML elements in order to manipulate them—allowing, for example, control of media
playback or animations to be triggered.
For a richer and more powerful experience, you can also program an application that is ren-
dered by the control using the new .NET Framework CLR. In addition to what you can do in
JavaScript, this capability offers many of the namespaces and controls that come as part of
the .NET Framework, allowing you to do things that are either very difficult—or not possible—
in JavaScript, such as accessing data with ADO.NET and LINQ, communicating with Web Ser-
vices, building and using custom controls, and so on.
Silverlight Architecture
Presentation .NET Runtime
XAML Networking/Data
A/V Media Codecs CLR App Domain
Browser Plug-In
Additionally, the presentation runtime ships with the software necessary to allow technologies
such as WMV, WMA, and MP3 to be played back in the browser without any external de-
pendencies. So, for example, Macintosh users do not need Windows Media Player to play
back WMV content—Silverlight is enough. Underpinning the entire presentation runtime is
the presentation code, and this manages the overall rendering process. This is all built into the
browser plug-in that is designed to support the major browsers available for both Windows
and the Macintosh.
The architecture of a simple application running in the browser using Silverlight is shown in
Figure 1-3.
Chapter 1 Introducing Silverlight 2 7
METHOD CALLS
METHOD CALLS
RENDER
EVENTS
EVENTS
Silverlight Plug-In
HTML Markup
As the application runs within the browser, it is typically made up of HTML. This markup con-
tains the calls to instantiate the Silverlight plug-in. As users interact with the Silverlight appli-
cation, they raise events that can be captured by either JavaScript or.NET Framework func-
tions. In turn, program code can make method calls against the elements within the Silverlight
content to manipulate it, add new content, or remove existing content. Finally, XAML can be
read by the plug-in and rendered. The XAML itself can exist inline in the page, externally as a
static file, or as dynamic XAML returned from a server.
XAML is an XML-based language that is used to define the visual assets of your application.
This includes UIs, graphical assets, animations, media, controls, and more. It was introduced
by Microsoft for the Windows Presentation Foundation (WPF), formerly Avalon, which is a
desktop-oriented technology and part of the .NET Framework 3.0 and beyond. It’s designed,
as discussed earlier, to bridge the gap between designers and developers when creating
applications.
The XAML used in Silverlight differs from that in the WPF in that it is a subset that is focused
on Web-oriented features. So, if you’re familiar with XAML from the WPF, you’ll notice some
missing tags and functionality, such as the <Window> element.
XAML uses XML to define the UI using XML elements. At the root of every Silverlight XAML
document is a container element, such as a Canvas, that defines the space on which your UI
8 Part I Introducing Silverlight 2
will be drawn. When building a Silverlight Web application, you’ll have a root Canvas that
contains the XML namespace declarations that Silverlight requires.
Here’s an example:
<Canvas
xmlns="http://schemas.microsoft.com/client/2007"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Width="640" Height="480"
Background="White"
>
</Canvas>
You will notice that two namespaces are declared. The typical XAML document contains a
base set of elements and attributes as well as an extended set, which typically uses the x: pre-
fix. An example of an extended namespace attribute is the commonly used x:Name, which is
used to provide a name for a XAML element, allowing you to reference it in your code. The
root Canvas element declares the namespace location for each of these.
The Canvas element is a container. This means that it can contain other elements as children.
These elements can themselves be containers for other elements, defining a UI as an XML
document tree. So, for example, the following is a simple XAML document containing a Can-
vas that contains a number of children, some of which are Canvas containers themselves:
<Canvas
xmlns="http://schemas.microsoft.com/client/2007"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Width="640" Height="480"
Background="Black"
>
<Rectangle Fill="#FFFFFFFF" Stroke="#FF000000"
Width="136" Height="80"
Canvas.Left="120" Canvas.Top="240"/>
<Canvas>
<Rectangle Fill="#FFFFFFFF" Stroke="#FF000000"
Width="104" Height="96"
Canvas.Left="400" Canvas.Top="320"/>
<Canvas Width="320" Height="104"
Canvas.Left="96" Canvas.Top="64">
<Rectangle Fill="#FFFFFFFF" Stroke="#FF000000"
Width="120" Height="96"/>
<Rectangle Fill="#FFFFFFFF" Stroke="#FF000000"
Width="168" Height="96"
Canvas.Left="152" Canvas.Top="8"/>
</Canvas>
</Canvas>
</Canvas>
Here you can see that the root Canvas has two children, a Rectangle and another Canvas. This
second Canvas also contains a Rectangle and a Canvas, and the final Canvas contains two
Chapter 1 Introducing Silverlight 2 9
more Rectangles. This hierarchical structure allows for controls to be grouped together logi-
cally and to share common layout and other behaviors.
Silverlight XAML supports a number of shapes that can be combined together to form more
complex objects. You’ll find a lot more details about using XAML in Chapter 4, “XAML Basics,”
but a few of the basic shapes available include the following:
In this case, the brush uses one of the 141 Silverlight-supported named colors, Black. You also
can use standard hexadecimal RGB color notation for custom colors.
Fills and strokes also may have a gradient fill, using a gradient brush. The gradient is defined
by using a number of gradient stops across a normalized space. So, for example, if you want a
linear gradient to move from left to right—phasing from black to white through shades of
gray—you would define stops according to a normalized line. In this case, consider the be-
ginning of the normalized line as the 0 point and the end as the 1 point. So, a gradient from
left to right in a one-dimensional space has a stop at 0 and another at 1. Should you want a
gradient that transitions through more than two colors—from black to red to white, for ex-
ample—you would define a third stop somewhere between 0 and 1. Keep in mind that when
you create a fill, however, you are working in a two-dimensional space, so (0,0) represents the
upper-left corner, and (1,1) represents the lower-right corner. Thus, to fill a rectangle with a
gradient brush, you would use a LinearGradientBrush like this:
<Rectangle Width="200" Height="150" >
<Rectangle.Fill>
10 Part I Introducing Silverlight 2
XAML also supports text through the TextBlock element. Control over typical text properties
such as content, font type, font size, wrapping, and more are available through attributes. Fol-
lowing is a simple example:
<TextBlock TextWrapping="Wrap" Width="100">
Hello there, how are you?
</TextBlock>
Objects can be transformed in XAML using a number of transformations. Some of these in-
clude the following:
XAML supports animations through defining how their properties are changed over time us-
ing a timeline. These timelines are contained within a storyboard. Different types of animation
include:
Beyond this basic XAML, you will define your full UIs using controls and layout using XAML,
too. These will be explored in more detail in Chapter 7, “Silverlight Controls: Presentation and
Layout,” and in the rest of the chapters in Part 2 “Programming Silverlight 2.”
x Expression Web This is a Web design tool that allows you to use HTML, DHTML, CSS,
and other Web standard technologies to design, build, and manage Web applications.
x Expression Media This is a media asset management tool that permits you to catalog
and organize these assets, including the facility to encode and change encoding between
different formats.
x Expression Encoder This application is designed to allow you to manage encoding of
media assets. It can also be used to bundle media with the relevant code to have a Silver-
light media player for it.
x Expression Design This is an illustration and graphic design tool that you can use to
build graphical elements and assets for Web and desktop application UIs.
x Expression Blend This tool is designed to let you build XAML-based UIs and applica-
tions for the desktop with WPF or for the Web with Silverlight.
When using Silverlight, you’ll use some or all of these applications. In the rest of this chapter,
we’ll take a look at how Design, Blend, and Encoder enhance your toolkit in designing and
building Silverlight applications.
Figure 1-4 shows the Export XAML dialog box in Expression Design. There are several format op-
tions, one of which is XAML Silverlight Canvas (shown selected). This option will format your
drawing using the subset of XAML elements that are usable by Silverlight, allowing you to import
the resulting XAML into Visual Studio or Expression Blend to build your Silverlight application.
Chapter 1 Introducing Silverlight 2 13
This will export the content as an XML document containing a Canvas element that contains
the elements of your design. Here’s a (truncated) example:
<?xml version="1.0" encoding="utf-8"?>
<Canvas xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" x:Name="Document">
You can then cut and paste this XAML into Expression Blend or Visual Studio, and you will be
able to use the graphical element in your application.
x Silverlight 1 Site This creates a Silverlight JavaScript project, giving you a folder that
contains a simple Web application containing an HTML page that has the requisite scripts
to embed a Silverlight object as well as a default XAML document containing a single can-
vas. It does not contain any of the implementation details for .NET programming, so the
descriptive term 1 Site is used, even though the Silverlight control is still version 2. This will
likely change in future versions of Expression Blend to Silverlight JavaScript Site. Chapter 6,
“The Silverlight Browser Control,” will look at programming JavaScript applications in a lit-
tle more detail.
x Silverlight 2 Application This creates a Silverlight project with everything necessary to
program against it using the .NET Framework. There will be more on Silverlight 2 in Chap-
ter 3, “Using Visual Studio with Silverlight 2,” and then Part 2 of this book (Chapters 7–14)
will cover it in much more detail.
In addition, Blend also creates a basic XAML page called Page.xaml and an associated Java-
Script file called Page.xaml.js. Expression Blend treats this as a “code-behind” JavaScript file in
a manner that is similar to how Visual Studio treats the C# code-behind file associated with an
ASPX page. Finally, Blend gives you a copy of the Silverlight.js file that is part of the Silverlight
software development kit (SDK). This file manages the instantiation and downloading of the
Silverlight plug-in for your users. You can see the project structure in Figure 1-6.
source: "Page.xaml",
parentElement: document.getElementById("silverlightControlHost"),
id: "SilverlightControl",
properties: {
width: "100%",
height: "100%",
version: "1.0"
},
events: {
onLoad: Silverlight.createDelegate(scene, scene.handleLoad),
onError: function(sender, args) {
var errorDiv = document.getElementById("errorLocation");
if (errorDiv != null) {
var errorText = args.errorType + "- " + args.errorMessage;
if (args.ErrorType == "ParserError") {
errorText += "<br>File: " + args.xamlFile;
errorText += ", line " + args.lineNumber;
errorText += " character " + args.charPosition;
}
else if (args.ErrorType == "RuntimeError") {
errorText += "<br>line " + args.lineNumber;
errorText += " character " + args.charPosition;
}
errorDiv.innerHTML = errorText;
}
}
});
}
if (!window.Silverlight)
Silverlight = {};
Silverlight.createDelegate = function(instance, method) {
return function() {
return method.apply(instance, arguments);
}
}
</script>
</head>
<body>
<div id="silverlightControlHost">
<script type="text/javascript">
createSilverlight();
</script>
</div>
<div id='errorLocation'></div>
</body>
</html>
As you can see, it imports two JavaScript files: Silverlight.js and Page.xaml.js. You’ll be looking
at each of these files shortly.
Chapter 1 Introducing Silverlight 2 17
The Silverlight control instantiation takes place in the <div> at the bottom of the page. This
contains a call to the createSilverlight function, which is implemented at the top of the page.
This creates a new Silverlight object using either the createObjectEx function (which, in turn,
resides in Silverlight.js) or the createObject function. When using the createObjectEx function,
the syntax for specifying the parameters uses the JavaScript Object Notation (JSON) syntax, as
shown in this example. You can alternatively use the createObject function, which uses stan-
dard parameters.
The first parameter is the source XAML. This can be a reference to a static external file (which
is used in this case as Page.xaml), a reference to the URL of a service that can generate XAML,
or a reference to a named script block on the page that contains XAML.
The second parameter is the parent element. This is the name of the <div> that contains the
Silverlight control. As you can see in Listing 1-1, this is called SilverlightControlHost.
The third parameter is the ID that you want to use for this control. If you have multiple Silver-
light controls on a page, you need to have a different ID for each.
The fourth parameter is the property settings for the control properties. These can include
simple properties such as width, height, and background color, as well as complex ones. More
complex property settings include:
x inplaceInstallPrompt Determines the install type for Silverlight. If this is set to true, the
user implicitly accepts the license and directly downloads and installs the plug-in. If it is set
to false, the user is directed to http://www.silverlight.net and, from that site, can accept the
license and download the plug-in.
x isWindowless If set to true, the control is considered windowless, meaning that you can
overlay non-Silverlight content on top of it.
x framerate Determines the maximum frame rate for animations.
x version Determines the minimum Silverlight version your application will accept. As you
can see in Listing 1-1, the version is listed as 1.0—this isn’t a bug, but simply an instruction
that this application is backward compatible and should work on 1.0. If this was instead
2.0, and Silverlight 2 was not installed, then the user would be taken to the install experi-
ence for Silverlight 2.
The fifth parameter is used to map events to event handlers. The events are implemented in a
JavaScript class called scene, which was declared at the top of the function:
var scene = new SilverlightSite1.Page();
18 Part I Introducing Silverlight 2
The createSilverlight function declares that the onLoad event should be handled by a member
function of the scene class called scene.handleLoad. It does this by creating a delegate using
this syntax:
onLoad: Silverlight.createDelegate(scene, scene.handleLoad)
This class is implemented in the JavaScript code-behind for Page.xaml called Page.xaml.js. You
can see this in Listing 1-2.
LISTING 1-2 JavaScript Code-Behind Page.xaml
if (!window.SilverlightSite1)
SilverlightSite1 = {};
SilverlightSite1.Page = function()
{
}
SilverlightSite1.Page.prototype =
{
handleLoad: function(control, userContext, rootElement)
{
this.control = control;
Here you can see JavaScript code to create a class called SilverlightSite1.Page. It contains two
member functions, handleLoad and handleMouseDown.
The function handleLoad adds another event listener for the MouseLeftButtonDown event by
creating a delegate associating this event and the handleMouseDown function, which is also
defined within this JavaScript.
Thus, the template application creates a default HTML file that contains an instance of Silver-
light with a single canvas that fires an event when it loads. The load event wires up the mouse
down event, demonstrating that event declaration, delegation, and handling are available at
both design time and run time.
Chapter 1 Introducing Silverlight 2 19
Expression Encoder allows you to import video from any format for which a DirectShow filter is
available and installed in your system. It will then re-encode the video into a VC-1–capable
WMV using one of a number of preset profiles optimized for the delivery client. These include
settings for devices, as well as for streaming or on-demand content delivered over the Internet.
You aren’t limited to what the preset profiles give you—you can override any of the video
and audio encoding settings. Figure 1-8 (on page 20) shows an example of how a video en-
coding may be tweaked.
Media Encoder includes a number of preset media player applications for Silverlight. These
will “wrap up” your video with a Silverlight JavaScript-based application that can be used on
any Web server to provide a complete Silverlight-based viewing experience.
In addition to encoding, metadata can be added to your video. A classic metadata experience
is when tags are encoded into the video and the application then reacts to these tags. Insert-
ing tags with Expression Encoder is very simple. Simply drag the playhead to the desired
point, select Add Marker, and enter the appropriate information for the marker.
20 Part I Introducing Silverlight 2
You can see this in Figure 1-9 on the right side of the screen, where the marker time and type
of ball that is shown on the screen at that time has been configured.
The Output tab allows you to select the template player that you want to use.
Figure 1-10 shows where the template that matches the Expression product line has been se-
lected. To create a video player with this template, simply import a video, and press the En-
code Button with this template selected.
After you’ve done this, you’ll get a full-featured media player in Silverlight for your video con-
tent. You can see an example of a Silverlight media player in Figure 1-11.
This section just scratches the surface of what is possible with Expression Encoder and how it
can be used with Silverlight. For more details, please refer to
http://www.microsoft.com/expression.
22 Part I Introducing Silverlight 2
Summary
In this chapter, you were introduced to Silverlight 2 and learned how it fits into the overall
Web and UX landscape. You discovered how technology from Microsoft is applied to current
UX scenarios, and you were introduced to an overview of the Silverlight architecture, includ-
ing XAML and how it is used to implement rich UIs.
Additionally, you saw how the Microsoft Expression Suite is designed to complement tradi-
tional development tools such as Visual Studio for creating Silverlight applications. You spe-
cifically learned how Expression Design is used to build graphical assets and how Expression
Blend is used to link these together into an interactive application as well as using Expression
Encoder to manage your video assets.
Now it’s time to go deeper. In the next few chapters, you’ll learn more about the Silverlight
API, starting with a more detailed examination of Expression Blend and how it is used by Sil-
verlight in the next chapter.
Chapter 2
Using Expression Blend with
Silverlight 2
Expression Blend is a professional design tool intended to create engaging experiences for
Windows and the Web. It allows you to blend all the necessary design elements for your Web
experiences, including video, vector art, text, animation, images, and other content such as
controls, with one set of tools. Expression Blend is designed to aid you in the building of Win-
dows-based as well as Web-based applications. This chapter will introduce you to this tool,
giving you a tour of what is possible with it. Expression Blend has far too many aspects to
cover in one chapter, but by the end of this chapter, you’ll have a good grasp of the basics
and will be ready to delve further into the features of this wonderful tool on your own!
After you’ve downloaded and installed Expression Blend, launch it from the Start menu. You’ll
see the Blend integrated development environment (IDE), as shown in Figure 2-1.
To create a new application, select New Project from the File menu to open the New Project
dialog box, as shown in Figure 2-2.
23
24 Part I Introducing Silverlight 2
You can see the project structure that it creates in Figure 2-3. This is identical to the product
structure that is built by Visual Studio, which will be discussed in much more detail in Chapter
3, “Using Visual Studio with Silverlight 2.”
What’s important to note about the structure is that there are two XAML files in this applica-
tion, and neither of them are a Silverlight XAML page, as in Silverlight 1. This is one way in
which a Silverlight 2 Application project differs fundamentally from a Silverlight 1 Site project.
You’ll see a small difference between this XAML and that created by Microsoft Visual Studio
(in Chapter 3). For example, this XAML has a few extra namespace declarations. Blend uses
these for parsing the XAML to render in the designer. They don’t affect your design beyond
that, and you can safely ignore these.
You’ll see that UserControl1 has a code-behind file that is generated for you. This will be
named UserControl1.xaml.cs or UserControl1.xaml.vb, depending on which language you se-
lected when creating the project. The file contains the basic code required to construct the
UserControl. You can see it here:
using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
namespace TestApp
{
public partial class UserControl1 : UserControl
{
public UserControl1()
{
// Required to initialize variables
InitializeComponent();
}
}
}
You aren’t restricted to using this file for your application logic. You can, of course, create oth-
er .cs (or .vb) files that can contain shared logic, but this one will be launched whenever the
control is instantiated by the Silverlight runtime.
Chapter 2 Using Expression Blend with Silverlight 2 27
This is accomplished using the OnStartup and OnExit events. These are set up for you by the
project template. Note that UserControl1 does not render by default—it has to be instructed
to render as part of the applications startup. This is accomplished in the OnStartup event han-
dler, where the RootVisual for the application is set to an instance of UserControl1:
public App()
{
this.Startup += this.OnStartup;
this.Exit += this.OnExit;
InitializeComponent();
}
App.xaml does not support visual elements directly, so you cannot add controls or other vis-
ual elements directly. Just because it is XAML, don’t think of it as a design surface. In this case,
XAML is used for definition purposes only. For example, you can define application-specific
resources for your application using it.
App.xaml.cs is useful for initialization of data that you want to use across several user controls.
Keep this in mind as you design your application. For example, you could store some text that
could be used across your application by declaring it as a resource in your App.xaml:
<Application
xmlns="http://schemas.microsoft.com/client/2007"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
x:Class="TestApp.App">
<Application.Resources>
<TextBlock x:Key="txtResource" Text="Hello"></TextBlock>
</Application.Resources>
</Application>
You can now easily access this content from any control in your application as follows:
TextBlock t = (TextBlock)Application.Current.Resources["txtResource"];
string strTest = t.Text;
28 Part I Introducing Silverlight 2
Before going any further, add a simple TextBlock to your UserControl to render some text.
Here’s an example:
<UserControl
xmlns="http://schemas.microsoft.com/client/2007"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
x:Class="TestApp.UserControl1"
d:DesignWidth="640" d:DesignHeight="480">
Now if you execute the application, you’ll see something like the output shown in Figure 2-4.
This simple application runs using the Cassini Web server (hence the random port number,
55924, that you can see in the address box in Figure 2-4) by generating an HTML page to
host the Silverlight content.
Let’s take a look at the source code for this page by using the browser command View Source.
You can see the source code here:
<!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>
Chapter 2 Using Expression Blend with Silverlight 2 29
<style type="text/css">
html, body {
height: 100%;
overflow: auto;
}
body {
padding: 0;
margin: 0;
}
#silverlightControlHost {
height: 100%;
}
</style>
<script type="text/javascript">
function onSilverlightError(sender, args) {
if (args.errorType == "InitializeError") {
var errorDiv = document.getElementById("errorLocation");
if (errorDiv != null)
errorDiv.innerHTML = args.errorType + "- " + args.errorMessage;
}
}
</script>
</head>
<body>
<div id='errorLocation' style="font-size: small;color: Gray;"></div>
<div id="silverlightControlHost">
<object data="data:application/x-silverlight,"
type="application/x-silverlight-2-b1" width="100%" height="100%">
<param name="source" value="TestApp.xap"/>
<param name="onerror" value="onSilverlightError" />
<param name="background" value="white" />
<a href="…"
style="text-decoration: none;">
<img src="…"
alt="Get Microsoft Silverlight" style="border-style: none"/>
</a>
</object>
<iframe style='visibility:hidden;height:0;width:0;border:0px'></iframe>
</div>
</body>
</html>
Do take note of the <object> tag. This attempts to instantiate Silverlight, and should it fail, it
renders an image with a hypertext reference (HREF) to the Silverlight download in its place.
You’ll see more about this and other ways of instantiating the Silverlight object in Chapter 6,
“The Silverlight Browser Control.”
30 Part I Introducing Silverlight 2
The IDE has two main application workspace layouts: the Design workspace, which is used
primarily for constructing and customizing your user interface (UI), and the Application work-
space, which is used primarily for designing your timeline-based animations. You can switch
between the workspaces using the F6 key or by selecting the workspace you want from the
Active Workspace options on the Window menu.
The screen is divided into panes in the Expression Blend IDE, and each of the panes has a fixed
purpose, as you’ll discover when we tour them now.
In Blend, similar tools can be collected together into a single icon on this tool pane. If you
look at Figure 2-5, you can see how to view a set of similar tools by finding the white triangle
Chapter 2 Using Expression Blend with Silverlight 2 31
in the lower-right corner of the tool. When this triangle is present, you can hold down the
mouse button on that tool to find more members in the same “family” as the selected object.
So, for example, if you hold down the mouse on the Rectangle tool, you’ll see a pop-up box
that shows you the other available shapes, as you can see in Figure 2-6.
One nice shortcut that Blend provides is the way it creates a default tool on the toolbar when
you have used a tool from the family of tools. That is, the tool that you just used will be dis-
played on the toolbar, so you don’t need to hold down the mouse, wait for the menu, and
then select the tool again to use it the next time.
So, for example, in Figure 2-6, the Rectangle is displayed on the toolbar, and when you hold
down the mouse, you will see a box displaying the other visual element tools of this type that
are available. If you then select the Ellipse and draw with it on the design surface, the toolbar
will change to display the Ellipse instead of the Rectangle.
x View all of the objects on your design surface, including their hierarchy when you are
using container objects.
x Select objects so you can modify them. This isn’t always possible on the design surface
because objects can be placed off screen or behind other objects.
x Create and modify animation timelines. You’ll learn more about how to do this in the sec-
tion titled “Using Blend to Design Animations” later in this chapter.
The interaction pane is designed to have two separate highlights. The currently selected ob-
ject is highlighted in grey—in Figure 2-7, you can see that the Border control is highlighted in
grey. This is the object that you can currently amend with the properties window or by drag-
ging it around the design surface.
Although it appears grey in the figure, you can see on your screen that the LayoutRoot control
has a yellow border around it. On the design surface, you’ll also see this yellow border. This
indicates that this is the currently selected container.
In addition to manipulating objects, you also use the interaction pane to create animations
and storyboards. You do this by clicking on the plus sign (+) button at the top of the interac-
32 Part I Introducing Silverlight 2
tion pane. You’ll explore the ways you can use this to create animations in the section titled
“Using Blend to Design Animations” later in this chapter.
On the right side of the design pane, you will see three tabs:
Note that you can use the Zoom feature in design view, so when you are working on sophisti-
cated interfaces, you can zoom in for a detailed view and zoom out for an overview. You do
this using the Zoom tool at the lower-left corner of the design pane. You can drop it down to
select preset zoom settings, type the specific value you want in the box provided, or drag the
mouse within it to set the desired zoom level.
A solution is a collection of one or more projects. When you edit a solution, you can manage
everything to do with the solution itself, including building, debugging, cleaning, and manag-
ing individual projects. In Figure 2-9, you can see the solution TestApp listed at the top of the
project pane, and the pane indicates that there is one project within the solution.
A project is a collection of items that, when combined, make up an application that contains
one or more Silverlight Pages. The project definition contains all the references to external
components that this application needs within the References folder. When you right-click the
project, the context menu that displays for the project allows you to manipulate the contents
of the project, with options such as adding new items based on a template, adding existing
items from other projects, or deleting items from the project.
The References folder within the project is used to manage references to precompiled assem-
blies that contain information that you want to use in your project. For example, if you want
to use a custom control, it will be compiled into an assembly, so if you reference that assem-
bly in your references, you can then use it within your application.
The Properties folder contains the application manifest file that describes all the properties of
the project, including the list of references, so that the application can understand from where
they are loaded at run time. The Properties folder should not be confused with the properties
pane, indicated by the Properties tab at the top of the window shown in Figure 2-9 and ex-
plained in more detail in the following section.
Chapter 2 Using Expression Blend with Silverlight 2 35
The first shortcut is provided by the division of the properties pane into several classifications,
typically providing access to the following visual aspects of elements:
x Brushes Allow you to set fill and stroke options as well as use an opacity mask on your
element. You’ll see a lot more detail about how brushes are used in Chapter 4, “XAML
Basics.”
x Appearance Allows you to set extended appearance properties for your object. Note
that the available appearance properties will change drastically based on the object that
you are currently editing. So, for example, if you are editing a Rectangle element, the Ap-
pearance section of the properties pane will allow you to set things like the corner radii,
but if you are editing a Button element that doesn’t have corner radii, you will not have
this option available.
x Layout Allows you to edit the various layout options for your object, such as Width,
Height, and Alignment options. You can also use layout options to change the position of
an object within a grid—if the layout is on a grid.
x Common Properties Effectively the properties that are common across a type of object.
So, for example, the common properties for controls that are distinct from shapes are typ-
ically edited here. These options can be very difficult to use, depending on the object that
you are editing. For example, if you are editing a control, a common property will be its
tab index, but if you are editing a shape, the tab index will not be available.
x Transform Provides you with the ability to edit the RenderTransform of your object. This
defines how the object can be manipulated by the rendering system. Transformations are
covered in detail in Chapter 5, “XAML: Transformation and Animation.”
x Miscellaneous The catch-all location for properties that aren’t available on any of the
other classifications.
Do take note that these classification panes are further subdivided. You’ll notice that many of
them have an arrow at the bottom of the pane that can be used to expand and contract the
properties view. This allows you to hide lesser-used properties until you need them.
The second shortcut in the properties pane is its Search feature, which allows you to search for
a particular property. For example, if you know you want to edit some features of a font but
don’t know the name of the property itself, you can type font into the search engine, and the
classifications and available properties will be filtered so that only those that have to do with
fonts are displayed. This is done immediately upon a keystroke, so if you are searching for a
font property—in our example, as soon as you type fo—you will see available properties dis-
36 Part I Introducing Silverlight 2
played such as foreground and rendertransform as well as the font properties, as shown in the
list of properties displayed at the bottom of Figure 2-10.
Now let’s take a look at how you can use all these tools we’ve introduced to build Silverlight
applications.
Layout
In Silverlight, you use special tools to create and organize the layout of your application.
There are several options available to you, and we will look at each of them in turn.
Chapter 2 Using Expression Blend with Silverlight 2 37
Using a Grid
The Grid layout element allows you to lay elements out in a structure that looks like a table.
(Do not confuse the Grid layout element with a Grid control that gives you functionality simi-
lar to a spreadsheet.) When using a Grid layout tool, you can specify how your elements are
placed by indicating their coordinates with virtual row and column designations within the
Grid layout. For example, consider the following XAML:
<Grid x:Name="LayoutRoot" Background="White" >
<Button Height="38" Margin="104,72,0,0" Width="58" Content="Button"/>
<Button Height="24" Margin="210,72,0,0" Width="54" Content="Button"/>
<Button Height="49" Margin="0,96,158,0" Width="80" Content="Button"/>
<Button Height="54" Margin="297,185,270,0" Width="67" Content="Button"/>
<Button Height="33" Margin="104,217,0,213" Width="87" Content="Button"/>
</Grid>
Now, if you wanted to organize these buttons, you could carefully set their positions by drag-
ging them around the design surface to place them at roughly the positions where you want
them, but if you position them this way, you will need to zoom in to make sure pixels are
aligned.
Alternatively, you could use the Grid layout, where you can use the layout properties of the but-
ton to determine its location in the grid. If you start with a new Silverlight project, you’ll see that
it has a Grid layout element on it called LayoutRoot. Select this element in your project, and look
at the Layout properties associated with it. Expand the properties viewer until you see the set-
tings for the ColumnDefinitions and RowDefinitions, as shown in Figure 2-12.
38 Part I Introducing Silverlight 2
Because ColumnDefinitions and RowDefinitions are collections, each one has an ellipsis (…)
button to the right of the setting name. This indicates that another dialog box will open
when you click it. Select the button next to the ColumnDefinitions property setting, and the
ColumnDefinition collection editor will display, as shown in Figure 2-13.
Use this dialog box to add, remove, and manage columns. Click the Add Another Item button
three times to add three columns. Repeat this for the RowDefinitions property setting so that
you have a grid that is comprised of three rows and three columns. After you have made
these changes to ColumnDefinitions and RowDefinitions, you will see that the designer pane
displays a 3 × 3 layout grid, as you can see in Figure 2-14.
Now, whenever you are placing an element on the screen, you’ll see pink guidelines that show
you how you can snap to a particular grid element, as shown in Figure 2-15. (They appear as
wider grey lines in the figure.) Snapping the button to the grid and column layout like this will
ensure that the button is always at that relative position and size in the grid.
Place another button in the central square on the grid, as shown in Figure 2-15. This time, do
not snap it to the grid. Then run the application and experiment with resizing the window.
You’ll see that the first button will always remain at the same relative position and the same
size, but the second button will change its width and/or height to stay relative to the size of
the screen.
40 Part I Introducing Silverlight 2
Using Canvas
The Canvas layout is a completely free-format drawing surface. You can specify the desired
location for a control by setting its Canvas.Top and Canvas.Left properties or by using its
Margin property.
You will see that the Canvas.Top and Canvas.Left properties for the button have been set.
These indicate that the button will always be at those values relative to the parent Canvas, so
as the Canvas moves, the button will move also. The Canvas layout is covered in more detail
in Chapter 4.
Using StackPanel
The StackPanel layout will always orient its child controls either horizontally or vertically,
stacking them (hence the name) based on the Orientation property. Note that the panel will
override the positioning of the controls. For example, look at the following XAML:
<StackPanel Height="337" Width="224">
<Button Canvas.Top="100" Height="64" Width="98"
Orientation="Vertical" Content="Button"/>
<Button Height="85" Width="92" Content="Button"/>
Chapter 2 Using Expression Blend with Silverlight 2 41
You can see that the first button has its Canvas.Top property set to 100. You would expect
that this would mean that the control would then be drawn at that position, but as Figure 2-
16 shows, this is not the case, and it is stacked by the StackPanel layout at the top of the
StackPanel (because the StackPanel has its Orientation property set to Vertical).
When you have many controls in a StackPanel, you may go beyond the bounds of the Panel
control itself, in which case the controls will be clipped to the bounds of the StackPanel. To
get around this problem, you can use a ScrollViewer, which is explained in the next section.
For example, following is a StackPanel in which the contents exceed the vertical space avail-
able to it:
<StackPanel Height="300" Width="199">
<Button Height="44" Width="86" Content="Button"/>
<Button Height="57" Width="75" Content="Button"/>
<Button Height="70" Width="59" Content="Button"/>
<Button Height="109" Width="95" Content="Button"/>
<Button Height="104" Width="88" Content="Button"/>
</StackPanel>
The StackPanel in this example is 300 pixels high, but the total height of all the buttons is 384
pixels, and so the bottom button will be cropped, as you can see in Figure 2-17.
42 Part I Introducing Silverlight 2
Now, if you contain this within a ScrollViewer, you’ll get better results. Note that the Stack-
Panel will still crop the buttons if you do not change its height, so if you need to have an area
of height 300, you can set the ScrollViewer to have this height and then set the StackPanel to
have a different height. Here’s the XAML to do this:
<ScrollViewer Height="300" Width="300">
<StackPanel Height="400" Width="199">
<Button Height="44" Width="86" Content="Button"/>
<Button Height="57" Width="75" Content="Button"/>
<Button Height="70" Width="59" Content="Button"/>
<Button Height="109" Width="95" Content="Button"/>
<Button Height="104" Width="88" Content="Button"/>
</StackPanel>
</ScrollViewer>
You can see how the ScrollViewer created here appears in Figure 2-18.
Now you can scroll up and down the button list, and the buttons will all be available; none are
unavailable because of cropping if you use the ScrollViewer. Note that the button at the bot-
tom in Figure 2-18 can be revealed by dragging the scroll bar down.
x Rectangle Select this shape to draw a straight-sided quadrilateral with 90-degree angles
at each corner. You can make a square by creating a Rectangle with equal width and
height properties.
x Ellipse Use this shape to draw an elliptical figure, an oval. You can make it a Circle by
making the width and height properties equal.
x Line This shape simply draws a straight line between two end points.
There are also tools available on the toolbar that you can use to create free-form shapes:
x Pen Use this tool to draw a set of connected line segments represented by an underly-
ing Path element.
x Pencil Use this tool to draw a set of connected elements, which can be lines or curves.
Blend will take the strokes that the user draws and represent them with an underlying
Path element.
Each of these visual elements, including those created with the Pen and Pencil tools, are rep-
resented by a single element, and this element can then be treated as any other object; that
is, you can modify it in many ways, including setting its properties or animating it. For
44 Part I Introducing Silverlight 2
example, consider Figure 2-19, in which the Pencil tool has been used to draw a set of con-
nected curves to create a representation of the word Hello in script. Look on the Objects And
Timeline view, and you’ll see the object represented as a Path.
Now, this pencil “drawing” of the word Hello is treated as a single object, so you can edit its
properties, including Fill, Brush, and so forth, simply by selecting it from the Objects And
Timeline view and then editing the properties in the property pane, as with any other object.
One thing to note is that Blend gives you two families of controls on the toolbar. The first in-
cludes the Text controls: TextBlock and TextBox. The second includes the set of basic user in-
terface controls: Button, CheckBox, ListBox, RadioButton, ScrollBar, Slider, and GridSplitter.
Finally, the toolbar gives you the option to add controls that aren’t part of this set. You can do
this by selecting the Asset Library link at the bottom of the toolbar. This will display the Asset
Library dialog box, as shown in Figure 2-20.
Chapter 2 Using Expression Blend with Silverlight 2 45
You can select controls in the Asset Library dialog box to add them to the toolbar. You also
can search for specific controls by entering the term in the search box. So, for example, if you
want to use a MediaElement control, start typing the letters of the control’s name. When you
see the control you want (in this case, the MediaElement), you can select it, and it will then be
available to you on the toolbar.
Then you can draw the control on the design surface and manipulate its properties with the
properties editor, as you have done with the visual elements and layout controls.
One form of animation that Silverlight supports is the DoubleAnimation, which is used to
change numeric properties, such as the width of an Ellipse visual element. Another is the Col-
orAnimation, which is used to change the color of the Brush property.
For example, consider the Ellipse shown in Figure 2-21 (which appears as a circle because its
height and width properties are equal). To visually design an animation that changes the
width of this Ellipse element, you’ll add a new Storyboard that contains the animation.
46 Part I Introducing Silverlight 2
On the Objects And Timeline view, select the Ellipse and then press the + button next to the
Storyboard list at the top of the pane. Accept the defaults in the Create Storyboard dialog box
that display, and then the Timeline editor will appear. You’ll also see the message Timeline
Recording Is On at the top of the Blend window. Press the F6 key to rearrange the workspace
so that the timeline is displayed to make it easier to work on an animation. Your screen
should look something like the one shown in Figure 2-22.
Look for the yellow line in the timeline view. This denotes the current position on the timeline.
Drag it to the 2-second mark, and then click the Record Keyframe tool at the top of the time-
line. It looks like a blob with a little green plus sign (+) at its lower-right side. You’ll see a little
oval that appears in the timeline at the 2-second mark, as shown in Figure 2-23.
Now that you have defined a keyframe, any changes that you make to the properties of the
object will be recorded at that key frame, so go ahead and change the width of the Ellipse
while the yellow line is still at the 2-second mark, indicating the current position of the time-
line. For example, change the width to 200 and the Fill color to Red.
Now drag the playhead (the top of the vertical yellow line on the timeline) left and right, and
you’ll see a preview of the animation previewed, with the width and color of the circle shape
changing over time.
Chapter 2 Using Expression Blend with Silverlight 2 47
You can see the XAML that is generated by your visual creation of the animation here:
<UserControl.Resources>
<Storyboard x:Name="Storyboard1">
<DoubleAnimationUsingKeyFrames Storyboard.TargetName="ellipse"
Storyboard.TargetProperty="(FrameworkElement.Width)"
BeginTime="00:00:00">
<SplineDoubleKeyFrame KeyTime="00:00:02" Value="200"/>
</DoubleAnimationUsingKeyFrames>
<ColorAnimationUsingKeyFrames Storyboard.TargetName="ellipse"
Storyboard.TargetProperty="(Shape.Fill).(SolidColorBrush.Color)"
BeginTime="00:00:00">
<SplineColorKeyFrame KeyTime="00:00:02" Value="#FFFF2200"/>
</ColorAnimationUsingKeyFrames>
</Storyboard>
</UserControl.Resources>
<Ellipse Height="100" Width="100" Fill="#FFFFF500" Stroke="#FF000000" x:Name="ellipse"/>
You’ll delve into the structure of this XAML in much more detail in Chapter 5, but the impor-
tant elements to note here are the Storyboard.TargetName instances that indicate which ele-
ment the animation is being defined for, and the Storyboard.TargetProperty that indicates the
property that is going to be changed. As you can see in this XAML, there are two animations,
one that changes the width of the target and the other that changes its color. Silverlight then
takes this definition and uses it to calculate the values required for each frame at the time the
animation is rendered.
Summary
In this chapter, you learned the basics of working with Expression Blend, taking a quick tour of
what it offers you as a designer or developer creating and implementing your own Silverlight
applications. You saw how Blend can be used to create Silverlight solutions and projects, and
then you saw what tools the Blend IDE offers you to add and manage visual elements, layout,
controls, and animations in your application.
We’ve just begun to investigate what you can do with Blend in this chapter, but your intro-
duction to Blend here may well inspire you to want to learn more about it.
The other half of the designer/developer workflow tool package is found in Visual Studio. In
Chapter 3, you’ll take a look at how you can use this tool, what it has in common with Blend,
and what powerful features it provides for developers. You will have the chance to use Visual
Studio to build your first Silverlight application—a sliding picture puzzle game.
Based on Beta 2—Updates Online
Introducing Microsoft ®
Silverlight 2
About the Author
™
Laurence Moroney is a Senior Technology
Evangelist at Microsoft, focusing on Silverlight
SECOND EDITION and the user experience. He has more than a
decade of experience in software development
Your first look at the tools and techniques for creating and implementation, and has written dozens of
rich Silverlight 2 experiences books and articles on Windows® Presentation
Foundation, Web development, security, and
Get a head start with Silverlight 2—the cross-platform, cross-browser interoperability.
plug-in for rich interactive applications and the next-generation user
experience. Featuring advance insights from inside the Microsoft
Silverlight team, this book delivers the practical, approachable
guidance and code to inspire your next solutions.
Developer Reference
• Expert coverage of core topics
• Extensive, pragmatic coding examples
Get C# and XAML code samples on the Web • Builds professional-level proficiency
with a Microsoft technology
For system requirements, see the Introduction.
Focused Topics
• Deep coverage of advanced
techniques and capabilities
• Extensive, adaptable coding examples
• Promotes full mastery of a
Microsoft technology
ISBN-13: 978-0-7356-2528-0
ISBN-10: 0-7356-2528-X
Part No. X14-55516