Exploring the Microsoft Client Continuum

A Beginner's Guide to Silverlight in Visual Studio

This lesson covers the basics of a Silverlight application with User Controls using Flash and MovieClips as its point of reference. While it can serve as an standalone tutorial for those new to working with Silverlight projects in Visual Studio, if you are already familiar with these steps, you may wish to skip ahead to next Lesson , Silverlight Animations with XAML & Code.

No doubt, one of the first lessons you built while learning ActionScript was adding a MovieClip to the stage in response to the user's actions. I generally think of it as the Hello World of dynamic visual programming and it probably looked something like this:

And the steps taken in Flash to create it went something like this:

  1. Create a new Flash Project with a script layer and single frame.
  2. Create a movieClip of a circle with the registration in the center.
  3. Export the circle movieClip for ActionScript.
  4. Write some code in the script layer that looked something like this:

Though these are the only lines of code you needed to write in Flash, there are many more lines of code for the visual definition of the ball. You just don't easily have access to them since you created your assets visually. Therefore, you can edit this ball definition visually in the Library of your Flash IDE, but you can't do a view source on it. And here is the first and deepest difference between Flash and Silverlight. Silverlight keeps the visual definition of all its elements in a text based markup language known as XAML. In this way, Silverlight is more conceptually similar to Flash's cousin Flex which does the same thing with it's MXML visual definition language.

So as we rebuild the above application in Silverlight to introduce ourselves to the Visual Studio development environment, we will be working with two types of files: the .XAML files that define the visuals for our stage and ball and the related code behind .CS files that hold the C# logic.

Let's get started. In Visual Studio, go to File > New Project > C# > Silverlight and select Silverlight Application from the Visual Studio Installed Templates. I named mine Lesson01_a. Pressing OK will take you to the Hosting prompt, where you should accept the default option of having Visual Studio add a Web Hosting Project to your solution for you. This makes it easier to debug your project in the same environment in which it will run online.

In your Solution Explorer, you will now see two projects, Lesson01_aWeb and Lesson01_a. You don't have to do anything with Lesson01_aWeb, it will do all the heavy lifting when you run (F5) your application. It will open your browser, act like a web server, and present your Silverlight application automatically if you've accepted all the defaults. The first time you run it, though, it will prompt you to allow debugging. Press OK to accept this.

You should now see two folders called Properties and References. You can ignore these for now. The two main files in our solution are App.xaml and Page.xaml. Each of these can be expanded further to reveal their code behind files, App.xaml.cs and Page.xaml.cs respectively. We won't be touching anything in App.xaml. Conceptually, you can think of App.xaml as the default Scene, and Page.xaml is the empty Stage that is first initialized. So let's focus on Page.xaml and Page.xaml.cs.

If you do decide to snoop around App.xaml.cs, you will find this line: this.RootVisual = new Page(); around Line 29. This is where App is told which User Control to show when the project is initialized. Page is defined in Page.xaml.cs, which is the default User Control created for you. It is technically the same as every other User Control you can create for yourself.

By default, Page.xaml always starts off with its LayoutRoot being of type Grid. Since in most of our lessons, though, we want to control the positioning of our dynamic elements directly as we do in ActionScript, we will usually change this LayoutRoot tag from a Grid to a Canvas. We will also change the Background property for this demo to #333333 to match the Flash movie we created above.

So your Page.xaml should now look like this:

To add a circle element, we can add the following tag between the open and close Canvas Tags:

Although I will be showing you the script for the visuals, I usually work with both Visual Studio and Expression Blend open at the same time. If you have installed Expression Blend as well, you can right click Page.xaml in the Solution Explorer in Visual Studio and select Open in Expression Blend... to draw the element instead of creating it with text as we just did. As the lessons progress, you may wish to jump into Blend to do visual tweaks on more complex graphics. This is also a great way to learn how to read XAML better by creating your resources visually in Blend and then exploring the resulting XAML markup it creates.

However, here is another subtle difference between Silverlight and Flash. In XAML, I can create a basic shape like this ellipse, name it and start interacting with it directly. In Flash, though, I can't name or talk to a shape I've drawn on the stage directly unless I first turn it into a MovieClip. We will see shortly how we can leverage our MovieClip experience with Silverlight User Controls. But for now, let's have our code talk directly to this ellipse shape we created and named ball.

In ActionScript, any code you have in the first frame will automatically be run and we're allowed to be a little sloppy with our variables (Personally, I think it's one of the reasons we artist types were so drawn to it! ActionScript 1.0 was very forgiving!). C#, on the other hand is an incredibly powerful language but it also requires you to be more specific in expressing what you want your code to do. So the easiest way to add startup code to Page.xaml is to go to the UserControl tag on the top and add a scripted event handler for Loaded like so:

No doubt you'll start to see what a rich development environment Visual Studio is. You can usually get away with pressing L then o then Enter and Tab to have the rest of the line auto completed for you. But pressing Tab not only completes the script line you were typing, it also creates the function definition for you in the code behind .CS file! You'll be amazed how quickly and accurately Visual Studio can help you type code once you get a hang of its powerful code hints and auto complete features

Press F7 to bring up the code behind file Page.xaml.cs and find the UserControl_Loaded() function already prepared for you. Just as we did in Flash, we want to create an event handler and assign it to a MouseDown event like so:

Again, we can leverage the auto complete features of Visual Studio and press Tab twice after typing + and =. Not only is the rest of the handler assignment line completed for you, but the function definition of the handler gets built out below for you as well. We can go next to that Page_MouseLeftButtonDown() function and type in the following logic:

This will move the shape we named ball to wherever the mouse is pressed. You can press F5 to run the application and see it work.

So far it's pretty basic, but don't forget that we're talking directly to a shape right now. We haven't even turned it into Silverlight's version of a MovieClip, the User Control. Let's do that next.

Right click on your Silverlight Project Lesson01_a in the Solution Explorer and go to Add > New Item... Make sure Silverlight User Control is selected, and name it Ball.xaml and press OK. You will now see Ball.xaml and it's code behind file Ball.xaml.cs in the Solution Explorer. If Ball.xaml didn't automatically open, double click on it now to see the XAML script in your work area.

If you want your XAML files to open in full XAML view and not in Design view or in Split window view, you can go to Tools > Options... > Text Editor > XAML > Miscellaneous and check the option Always open documents in full XAML view. This is especially helpful if you use Expression Blend as your visual editor and not Visual Studio's native Design view.

As we did with Page.xaml, convert the Grid tag to a Canvas tag and add an Ellipse shape. I'm also going to make the following changes:

  • Remove the the Width and Height attributes from the User Control tag, they're not needed for what we're doing.
  • Take out the Background="White" property in LayoutRoot as well. We want our User Control to have a transparent background, like new MovieClips in Flash do.
  • For the Ellipse shape we create inside Ball.xaml, let's change the Canvas.Left and Canvas.Top to -15. User Controls have their local registration point in the upper left hand corner (0,0). Since the Ellipse we create is 30px wide and 30px high, moving it left and up 15 pixels will align the origin of the circle with the registration point of the User Control.

Your Ball.xaml should now look like this.

Let's go back to Page.xaml and get rid of the Ellipse shape we put there, so that Page.xaml's LayoutRoot Canvas is empty again. While still on Page.xaml, press F7 to get to the Code Behind file Page.xaml.cs and let's modify Page_MouseLeftButtonDown() to look like this:

That's it. Run it with F5 and it should work just like the Flash movie. A side by side comparison of the actual code shows some similarities and difference between Actionscript 1.0 and C#:

ActionScript 1.0

C#

A couple differences to note. Like in ActionScript 3.0 (but not in our simplified ActionScript 1.0 example above), you need to add any visual elements you create in code by adding that element to the visual tree of something that is already visible on screen. In this case, we are using the Canvas named LayoutRoot as our primary root, so we add the Ball.xaml instance we created to its visual children to make it visible. As we will see in future lessons, since visual elements can have various transforms applied to them, the mouse position is usually queried relative to some point of reference. In this case, we are referencing our main stage Page.xaml directly with the request e.GetPosition(this). Finally, you will notice that Silverlight and WPF don't expose automatically the X and Y properties of their elements, but use a LeftProperty and TopProperty. Coming from Flash and the ease of typing _x or _y to position something on stage, this can feel very cumbersome at first. However, in the next lesson, this will be one of the first things we learn how to fix!

Here is our finished Silverlight version that mimics our Flash project:

We went a bit slowly in this lesson for those of you who have never worked with Silverlight projects in Visual Studio before. The next lessons, however, start to pick up speed, building on the previous lessons and making assumptions on what you have been learning. So if all this is brand new to you, you may want to review this first lesson a couple of times and experiment with it until you feel comfortable working your way around Visual Studio, creating a new Silverlight solution and Web Hosting project, adding a User Control and the differences between the XAML file and the Code Behind file.

Starting with the next lesson, we're going to jump right into programming animations in code, so come on over when you're ready.

Have a question or comment on this article? Have a suggestion for new content?
Send your feedback.
Microsoft Communities