Introduction to Silverlight 1.0: Building your first Silverlight application

This tip shows developers how to use Silverlight 1.0 and Expression Blend 2.0 to create their first Silverlight application.

It's hard to turn around without hearing something about Silverlight. It is likely time to begin looking at how

it works so you aren't left behind. Luckily Silverlight 1.0 is based on tried and true technologies. The markup is based on the Windows Presentation Foundation XAML design markup language and the programming is based on JavaScript. If you've had any exposure to these technologies, Silverlight should be breeze to pick up. If you haven't, Silverlight is a great way to get started with them. In this article I will walk you through writing your first simple Silverlight application to show a small video in a Silverlight application.

Getting started

Before you begin, you will need to get your development environment ready to write your first Silverlight application. While you can develop Silverlight without any tools, using Visual Studio 2005 or 2008 is recommended. In this article I will assume that you are using one of these versions of Visual Studio. If you do not have Visual Studio installed, I would recommend downloading and installing Visual Web Developer 2005 Express Edition. Tthis is free to use, and you can get it at the Visual Studio 2005 Express Editions page.

Once you have Visual Studio (or Visual Web Developer) installed, you will need several packages installed to actually do Silverlight development. These can all be found on the Getting Started section of Silverlight.net. There are three packages you should download and install; order is not necessarily important, but I usually do it in the following order:

  • Silverlight 1.0 Runtime (Windows)
  • Expression Blend 2 (Latest version, though as of this article it's the December Preview)
  • Microsoft Silverlight 1.0 Software Development Kit (SDK)

Installing each of these is pretty straightforward, but there are some things to note when you install the Silverlight 1.0 runtime.

More Silverlight 1.0 resources
Silverlight Learning Guide. v1.0 tutorials

Microsoft's Silverlight site

Getting Started with Silverlight

Visual Studio 2005 Express Editions download

Shawn Wildermuth's blog

Class-based JavaScript discussion
When you launch the Silverlight 1.0 Runtime Installer, you are installing the same runtime that Silverlight will prompt users to install when they visit their first Silverlight application. If you already have been viewing Silverlight applications, then you can skip this step. One caveat is that the installer is at times a little troublesome for some users. If you successfully install the runtime, please visit a test page (e.g. the the Silverlight Showcase on the ADOguy blog) to see if the runtime is installed correctly. If you still get the "Download Silverlight" button on the test page, please uninstall and reinstall, as this often solves the issue.

Optionally, you can also install the following for additional functionality (though we do not use them in this article):

  • Expression Design
  • Expression Media Encoder

Once you have everything installed, you are ready to write your first Silverlight application!

Writing your first Silverlight application

There are two ways to start a new Silverlight application -- using Visual Studio and using Expression Blend. It does not matter which one you use to create your application as they create essentially the same project structure.

Starting with Expression Blend 2.0

To get familiar with both applications, let's start with Expression Blend and move on to Visual Studio to add our code. When you first launch Expression Blend you are invited to open an existing or create a new project. Select new project as seen in Figure 1:

Figure 1: New Project in Expression Blend

Once you pick "New Project," you will be presented with a dialog where you can create your new project. Please pick the "Silverlight 1.0 Site" project and name it as seen in Figure 2:

Figure 2: New Project

Once the project is created, it leaves you in Expression Blend with a small Canvas on which to work. First, here's a quick tour of the important parts of the window:

  • On the left you will see the Tools, which includes drawing and selection tools.
  • In the middle of the screen will be the drawing surface. This is where you will likely spend most of your time actually creating the look of your Silverlight application.
  • To the left of the drawing surface is the "Objects and Timeline" window, which will show the hierarchy of the controls on the page.
  • Lastly, on the right side of the page is the project structure, which shows you the list of files associated with the project.

This can be seen in Figure 3. (Click on the thumbnail for a full-size image.)

Figure 3: Expression Blend 2.0

A Silverlight project is made up of a number of files that you can see in the Project panel (as shown in Figure 3). Initially the files that are created are as follows:

Default.html This is a test HTML page that hosts your Silverlight project.
Default_html.js This is the JavaScript that is used to place your Silverlight project on a page and load it into the browser.
Page.xaml This is the XML-based markup file that represents the look and feel of the Silverlight project.
Page.xaml.js This is the JavaScript file that contains the programming logic behind your Silverlight project.
Silverlight.js This is the Silverlight API that is used to host Silverlight on an HTML page. This is required but never edited by developers.

In Expression Blend we're going to focus on the Page.xaml file as that is the file that is being edited on the drawing surface. For our first Silverlight application, we will create a simple media player. Pick the rectangle tool and draw a rectangle over most of the page as seen in Figure 4. (Click on the thumbnail for a full-size image.)

Figure 4: Drawing a rectangle

Next, color the rectangle by using the property panel. Click on the Property tab in the right panel. In the property panel, there is a Brushes section that allows you to specify how to color the stroke and fill of the rectangle. Pick the Fill and color it light gray as seen in Figure 5.

Figure 5: Specifying the Fill

Next let's round the corners of the rectangle by using the radius handles in the top-left corner of the rectangle. If you grab the handle and drag, it will round the corners:

Figure 6: The radius handles

Change the rounding until the corner is just slightly rounded. (Click on the thumbnail for a full-size image.)

Figure 7: The rounded rectangle

Now we have a surface on which to create our video player. To play a video, we will need a video to show. Go to the menu and pick "Project->Add Existing Item" and find a video to add it to the project. (Silverlight does not need a video to be part of a project but it will make our quick demo easier). In our example we're going to use the Bear.wmv that ships with most versions of Windows. If you drag and drop the video from the Project panel onto the surface of the Silverlight design, it will create a new MediaElement with that video attached to it as seen in Figure 8. (Click on the thumbnail for a full-size image.)

Figure 8: Video added

At this point you can actually watch the video by pressing F5 to launch the Silverlight application, as seen in Figure 9. (Click on the thumbnail for a full-size image.)

Figure 9: Your first Silverlight application

Now that we have a working video player, let's add one more element to allow us to start the video. Pick the Pen tool and drag a large triangle over the video by clicking on each corner to make a triangle. To complete the triangle, make sure you click on the beginning point at the end. This means that making a triangle will take four clicks, one on each point then the beginning point again. The triangle is shown as it should look like in Figure 10. (Click on the thumbnail for a full-size image.)

Figure 10: Drawing the triangle

Once the triangle is created, name it 'playButton' in the Name box in the Property panel. Next let's color the triangle red by choosing Red in the Brush Editor. In addition, make the triangle semi-transparent by changing its "A" (or Alpha) channel to 50% on the right side of the Brush editor as seen in Figure 11.

Figure 11: Coloring the triangle

Before we start the development, one last task is to create a simple animation to make our triangle disappear. Creating animations in Blend is a matter of creating a Storyboard that will contain our animation. To do this, go to the menu and select "Window->Animation Workspace," which simply moves the Objects and Timeline bar to the bottom of the page. Next, find the + sign button next to the Storyboard text box at the top of the Objects and timeline (shown in Figure 12):

Figure 12: New Storyboard button

Once you click the new button, it will open a dialog to have you name the new Storyboard. This will be a name we use from the code to start this animation. Please name it "playButtonDisappear". Once you create the storyboard, Blend will be in "recording" mode. This mode allows you to specify points in time and change properties to create animations. Once you are in record mode, the designer surface is surrounded with a red rectangle and a record button is lit at the top right. In addition, there is a time line that is created next to your object hierarchy at the bottom of the screen. These elements are shown in Figure 13. (Click on the thumbnail for a full-size image.)

Figure 13: Recording mode enabled

Make sure that you have the playButton selected for these next operations (note that the playButton should be highlighted as is shown in Figure 13). Using the mouse, click the "1" in the timeline to move the yellow 'cursor' to the one second point in the timeline. Now go to property panel and change the Opacity of the triangle to 0% which will make it disappear. If you use the VCR-like controls above the timeline, you can go to the first frame and press play to watch the animation work. Press F5 to make sure the design is working. You should see the video play but you will *not* see the play button disappear. Close the Internet Explorer to return to Blend. Now that we have the animation in place, we can move on to Visual Studio to add the functionality to make it a fully working media player.

Silverlight in Visual Studio

Visual Studio and Expression Blend both use the same project files -- you can open Visual Studio solutions in Blend and Blend creates solution and project files when you create projects. In this way they can work very seamlessly together. It might seem odd that we have two different applications to do this, but the idea here is that Blend is more of a designer-level tool and Visual Studio is a developer-level tool. While both might use the other tools, it is feasible to allow the designers to create the look and feel and let the developer use Visual Studio to add the functionality.

With Expression Blend still open, right-click on the Project file (MyFirstSilverlight in the Project tab) and select "Edit in Visual Studio" to open the project in Visual Studio. Visual Studio may ask you about upgrading to the .NET Framework 3.5. For this example, it doesn't matter what you say, as we are not using any .NET in this example. Once it is opened in Visual Studio, you should see the same project with the same assets as we saw in Blend (as seen in Figure 14).

Figure 14: Your project in Visual Studio

Now that we have our project in Visual Studio, we want to add some code. Understanding the structure of code is important but is outside what we have time to dig into in this article. Instead we will write some code that should give you a taste of what coding in Silverlight 1.0 is like. All coding in Silverlight 1.0 is done by writing JavaScript (like in Web pages). If you are unfamiliar with JavaScript, feel free to just copy the code exactly to see it work.

Before we can add our code, we need to make a minor modification of the design markup. We need to open the Silverlight XAML file, but if you just double-click the .xaml file it will attempt to open it in the Windows Presentation Foundation designer. The problem is that the Silverlight XAML is not compatible with the WPF designer. Instead we want to open it in the XML editor, as that will provide us with IntelliSense for our XAML file. To open the markup, right-click the Page.xaml page and select "Open With…"; finally, select "XML Editor" to open it. You should see the XAML document as a simple XML file in Visual Studio now. Look through the file and find the MediaElement element which should be near the middle of the file. Directly after the "<MediaElement" part of the tag, add an attribute to stop the video from automatically playing by adding AutoPlay="False." In addition, find the x:Name attribute and change it to the Player. Your MediaElement should look like this:

<MediaElement x:Name="thePlayer" AutoPlay="False" Width="590" Height="439" 
Canvas.Left="24" Canvas.Top="23" Source="Bear.wmv" Stretch="Fill"/>

We can now close the Page.xaml file. Open the Page.xaml.js file to add our functionality. Find the line of the code that starts with handleLoad. This is the function that is called when the Silverlight control is loaded and where we will add our initialization code. The format of this code is class-style JavaScript. It uses the prototype functionality in JavaScript to create class-like structures to encapsulate our code. If this is confusing to you, feel free to look at the technique (see link in Resources below).

For our example we need to do a couple of steps. First we need to add member fields to our class for our named elements. We have three elements that we need to handle: thePlayer, playButton and the storyboard called playButtonDisappear. Silverlight supports a findName method that exists on most objects in Silverlight. This method will search the list of names defined in the XAML file and find the one that has a specific name. These names have to be unique within a single XAML document so that findName will always return the same object. The handleLoad function passed in a parameter called rootElement, which represents the root Canvas of our XAML file so we can use it to find our three elements and then make them members by prefixing them with the this keyword. After the assignment of the control field, add three new members using the findName method. Also remove any code between the last new field and the end of the function so your code should now look like this:

MyFirstSilverlight.Page.prototype =
{
  handleLoad: function(control, userContext, rootElement) 
  {
    this.control = control;
    
    this.thePlayer = rootElement.findName("thePlayer");
    this.playButton = rootElement.findName("playButton");
    this.playButtonDisappear = rootElement.findName("playButtonDisappear");
    
  },
  
  // Sample event handler
  handleMouseDown: function(sender, eventArgs) 
  {
    // The following line of code shows how to find an element by name 
    // and call a method on it.
    // this.control.content.findName("Storyboard1").Begin();
  }
}

Next we need to register for events. First, let's change the sample event handler to be ready for our event to call it. Change its name to playButtonClick (replacing handleMouseDown) so that it is aptly named for when the play button is clicked. Inside the event let's use the class-level fields to do the work of starting the video and starting the animation. We can do this by calling this.thePlayer.play() to start the video and calling this.playButtonDisappear.begin() to start the animation. The sample event handler should now look like so:

  // Sample event handler
  playButtonClick: function(sender, eventArgs) 
  {
    this.thePlayer.play();
    this.playButtonDisappear.begin();
  }

We want to be able use the playButtonClick method to be called when the playButton is clicked with the mouse. Most Silverlight objects support a method called addEventListener that enables us to register for events. This method takes a callback function to call once the event is fired. We can use a function called Silverlight.createDelegate() to create a callback to a class-based method (like playButtonClick). This is the pattern that registering for events. For example, lets register for the MouseLeftButtonUp event for the playButton by calling this.playButton's addEventListener method and creating a delegate to the playButtonClick method by using the Silverlight.createDelegate() like so:

MyFirstSilverlight.Page.prototype =
{
  handleLoad: function(control, userContext, rootElement) 
  {
    this.control = control;
    
    this.thePlayer = rootElement.findName("thePlayer");
    this.playButton = rootElement.findName("playButton");
    this.playButtonDisappear = rootElement.findName("playButtonDisappear");

    this.playButton.addEventListener("MouseLeftButtonUp", 
    Silverlight.createDelegate(this, this.playButtonClick));    
  },
  
  // Sample event handler
  playButtonClick: function(sender, eventArgs) 
  {
    this.thePlayer.play();
    this.playButtonDisappear.begin();
  }
}

The Silverlight.createDelegate() method specifies the instance of a class to use (and we want to use our own instance so we're using this) and the method to call when the delegate is executed (in this case the playButtonClick method). This simply means that when the mouse button is let go over the playButton that it will fire the playButtonClick method. Now if you run the project (by pressing F5 again) you'll see the completed project. When you click on the play button it will start the video and make the play button slowly disappear.

Conclusion

As has been evidenced by the early adopters, Silverlight is a fun but compelling technology to expand the functionality of typical HTML based websites. Microsoft has not only supplied the Silverlight runtime but has integrated with two well-worn tools -- Visual Studio and Expression. By using these tools you can get started writing your own Silverlight applications.

Download the source code for this article

Shawn Wildermuth is a Microsoft MVP (C#) and MCSD.NET. He is also a speaker on the INETA Speaker's Bureau and has appeared at several national conferences to speak on a variety of subjects. Wildermuth is also the author of several books including the book Pragmatic ADO.NET for Addison-Wesley, and is also the co-author of four Microsoft Certification Training Kits for MS Press, as well as the upcoming book Prescriptive Data Architectures as well as dozens of articles. He is currently teaching Silverlight across the country during his Silverlight Tour.


This was first published in February 2008

Dig deeper on Silverlight and Expression application development

0 comments

Oldest 

Forgot Password?

No problem! Submit your e-mail address below. We'll send you an email containing your password.

Your password has been sent to:

SearchCloudComputing

SearchSoftwareQuality

SearchSOA

TheServerSide

SearchCloudApplications

Close