Welcome to MSDN Blogs Sign in | Join | Help

Dev Girl's World

by Agata Staniak

Discovering the beauty of Silverlight development
Silverlight Basics #2: The anatomy of a “Hello world” application

After having read part 1 of this tutorial you already know a Silverlight application is actually an executable hosted by the Silverlight plugin, client side, in user's browser. It's time you created your first application and had a closer look at it.

After having read this part you will:

  • know where to find everything you need to get started with Silverlight,
  • know how to create a "Hello world" application and understand what is inside,
  • know how to embed the "Hello world" application in a website.

If you already know all of that, you can skip this part and move on straight to the next part.. Silverlight Basics #3: All roads lead to Rome - mixing XAML and C#.

Let's get started!

The Silverlight's home is here: http://silverlight.net. You will find all the resources to get started here: downloads, discussion forums, code samples, tutorial videos and much more. To start developing Silverlight applications you need these:

  • Visual Studio 2008 with SP1 (the service pack is very important) or Visual Web Developer Express with SP1
  • Silverlight Tools for Visual Studio 2008 SP1

These are the two essential things. There are of course more Silverlight related tools you can optionally download as well but we won't be using all of them here. I will be showing you how to use Blend later on, so it's useful if you install it as well:

  • Expression Blend 2
  • Service Pack 1 for Expression Blend 2 (once again, the service pack is very important)

Now go ahead, and get them all!

Creating a new Silverlight project

Now that you have everything setup and ready, it's time to make use of it. Open your Visual Studio 2008 SP1, and create a new Silverlight project:

  • Press Ctrl+Shift+N (or choose from menu: File » New » Project...). A New Project dialog window pops up:

    New Project window

  • In the New Project window:
    • Choose the project type on the left side: expand Visual C# and then click Silverlight.

If you can't see Silverlight on the list of supported Visual C# project types it means you didn't install Silverlight Tools for Visual Studio 2008 SP1 correctly. Try to close and reopen Visual Studio. If that doesn't help, close Visual Studio. Open Control Panel, select Add or Remove Programs (XP) or Programs and Features (Vista) and remove Microsoft Silverlight Tools for Visual Studio 2008 SP1. Then go back here, and install it again.

    • On the right side, choose the Silverlight Application template.
    • Name the project HelloWorld. Fill in the solution name and path as usual and click OK.

  • An Add Silverlight Application dialog window pops up:

Add Silverlight Application window

All this dialog box is asking you about is how you want to run your new application. As you remember from part 1, Silverlight application is hosted by a browser plugin, so it is embedded inside of a website. You cannot just run it standalone. You need a web page, with some HTML and a special Silverlight object embedded inside that HTML. You can create this web page manually or let Visual Studio take care of it, so that you can run your application by clicking Run. If you let Visual Studio do it, this dialog box asks you how you want your web page to be created. You can use a static HTML page that Visual Studio will generate for you each time you build your Silverlight Application. Or you can create an ASP.NET website. As you remember from part 1, ASP.NET is a server side technology and it generates HTML on the fly. ASP.NET website is more flexible and powerful but a bit more complex (you have to manage both server side and client side stuff in one solution). We will need it later, but for now let's just go for the simpler option.

In the dialog window choose Automatically generate a test page to host Silverlight at build time, and click OK.

Running the Silverlight project

At this point you should have an empty Silverlight project with the structure similar to this:

A silverlight application file structure

Now hit F5 to run the application. An Internet Explorer window shows up with an empty white page. To make sure it's actually a Silverlight application and not just an empty file, right click on the page. Instead of the familiar standard Internet Explorer popup menu you see the Silverlight popup menu, with only one element: Silverlight Configuration.

Standard Internet Explorer menu and Silverlight plugin menu

This means you clicked inside of the Silverlight plugin content. If you click Silverlight Configuration, you can set some options and check the version of Silverlight you have installed on your computer. The latest version at the moment I'm writing this is: 2.0.31005.0.

Embedding the Silverlight application in HTML

If you check the address of the page you opened by hitting F5, you can see it's just an HTML file, stored locally on your hard drive. Something like this:
C:\MySilverlightApps\HelloWorld\HelloWorld\Bin\Debug\TestPage.html.

You can open this file in any text editor or open it in Visual Studio (after you turn on Show All Files for your project). If you open it, you can see it is just a standard HTML file, nothing fancy there, except for one element:

<object data="data:application/x-silverlight,"
        type="application/x-silverlight-2"
        width="100%" height="100%">
      <param name="source" value="HelloWorld.xap"/>
      <param name="onerror" value="onSilverlightError" />
      <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>

This is how Silverlight applications are embedded in HTML: as objects. In this case there is only one object that takes up 100% of the window content. When your browser downloads HTML like this and parses it, it looks up the data and type of the object (application/x-silverlight) and runs the Silverlight plugin. The plugin takes care of the rest. It takes the parameters and knows how to display your application. In this example the plugin knows the application is in the HelloWorld.xap file (we will talk about what it is later) and the minimum Silverlight version for it to run is 2.0.31005.0. In case you don't have the required version of Silverlight installed on your computer, you will see an image with a link to the Silverlight download page. If your application encounters any problems, Silverlight plugin will notify you by calling the onSilverlightError Javascript function, which will display the error message.

You can modify this HTML file. Try for example putting this piece of HTML above the Silverlight object:

<p style="background-color: orange">Below is my first Silverlight application:</p>

Save the file but don't hit F5. Instead, just open the file in Internet Explorer. Notice the orange strip at the top of the page. If you right click on it, you will see a standard Internet Explorer menu. This is just simple static HTML content: you can copy the text, view HTML source etc. However when you right click on the white area below, you will see it is Silverlight content. Now you know how to mix HTML and Silverlight content on one page. But you have to remember one thing: the file you edited is just a simple test page for your application and is regenerated each time your project is built. Rebuild your project, and the changes you made are gone. If you need to embed your Silverlight application in a more fancy webpage than just an empty test page, you either have to create the webpage manually and embed the object manually (you already know how), or use the other option when creating a Silverlight project: Add a new ASP.NET Web project to the solution to host Silverlight.

Adding content to the Silverlight application

An empty white application gets boring quite quickly, so let's see how to add some content into it. As you probably already noticed, there are two classes in your HelloWorld project.

Open the App.xaml.cs file. The App class inherits from the Application class and it simply represents the entire Silverlight application. It has a method ReportErrorToDOM that displays Silverlight messages on the website through JavaScript. It also handles all uncaught exceptions by handling the UnhandledException event. And finally, on startup it sets the RootVisual property to a new instance of the Page class. RootVisual is the main element that displays application's content. By setting RootVisual to any UIElement, we say "display whatever this UIElement displays".

Open the Page.xaml.cs file now. The Page class is simply a user control. It could be named whatever, "Page" is just a name chosen by Visual Studio when it creates the first control for you. For your convenience, the Page class consists of two files: one for XAML definition and one for code. But you can as well create controls that do not contain XAML at all. Switch to the Page.xaml file now. You can see something like this:

<UserControl x:Class="HelloWorld.Page"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Width="400" Height="300">
    <Grid x:Name="LayoutRoot" Background="White">
    </Grid>
</UserControl>

Page is our root control, and it inherits from UserControl (as you saw it already in the Page.xaml.cs file). Its type is defined by the x:Class attribute. And its size is 400x300 pixels. Whatever content we want to display in the application, it needs to be inside of this control (in XAML) or set as the Content property of this control (in code). But it can only contain one element, for example one button only. Now you ask, what if I want to create more buttons? There are specialized controls that can contain more than one element as their content and we will talk about them later. Right now you should only know one of those controls is called Grid. That is why Visual Studio put a Grid for you in the Page class. You can now add some content to the Grid. Try putting some text inside. There is a TextBlock control you can use (new code highlighted with yellow marker):

<UserControl x:Class="HelloWorld.Page"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Width="400" Height="300">
    <Grid x:Name="LayoutRoot" Background="White">
        <TextBlock Text="Hello World!"
                   VerticalAlignment="Center"
                   HorizontalAlignment="Center" />

    </Grid>
</UserControl>

Hit F5 now and run the application. Yay, we finally display something! But why isn't the text centered on the screen? Wasn't the Silverlight plugin supposed to take up 100% of the window? Yes. The Silverlight plugin takes up entire window (you can easily check it by right clicking wherever and see it's still the Silverlight, not HTML, content). But the Page control was told to be 400x300 pixels size. Try changing its color to see where it actually fits:

<UserControl x:Class="HelloWorld.Page"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Width="400" Height="300">
    <Grid x:Name="LayoutRoot" Background="Yellow">
        <TextBlock Text="Hello World!"
                   VerticalAlignment="Center"
                   HorizontalAlignment="Center" />
    </Grid>
</UserControl>

Hit F5 now. You should now see exactly where the Page control fits on the screen. Our final "Hello Application" looks like this:

The final Hello World application

If you want the Page to take up the entire window, simply remove the Width and Height properties in your Page control:

<UserControl x:Class="HelloWorld.Page"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <Grid x:Name="LayoutRoot" Background="Yellow">
        <TextBlock Text="Hello World!"
                   VerticalAlignment="Center"
                   HorizontalAlignment="Center" />
    </Grid>
</UserControl>

And that's it! You have just created your first Silverlight application! And without typing a single line of C# code, all in XAML :)

Summary

You now know how to create a new Silverlight project and how to put some simple content into it. You should also understand how a Silverlight application is hosted in the browser window.

The source code of the final "Hello World" application: HelloWorld.zip.

Now it's time to move on to the next step.. Silverlight Basics #3: All roads lead to Rome - mixing XAML and C#

Posted: Sunday, December 21, 2008 7:06 PM by agaace
Attachment(s): HelloWorld.zip

Comments

Community Blogs said:

In this issue: Steve Commisso, Silverlight Girl, Tim Greenfield, Damon Payne, and Agata Staniak(2). Shoutout

# December 25, 2008 5:15 PM
Anonymous comments are disabled
Page view tracker