Click here to Skip to main content
15,884,473 members
Articles / Programming Languages / C#
Article

Beginning Silverlight 1.1 Part 1

Rate me:
Please Sign up or sign in to vote.
4.72/5 (61 votes)
12 Oct 200712 min read 206.5K   907   124   32
Describing basic Silverlight principles

Introduction

With this article, I want to start a Beginning Silverlight series in which I'll try to share with you my experience in such a great technology. I'll start with Silverlight basic principles and finish with some amazing Silverlight applications. Let's start step-by-step.

Using the Code

To use code from this article, you will need to install Visual Studio 2008 Beta 2 and Microsoft Silverlight Tools Alpha for Visual Studio 2008 Beta 2. After installing them, simply open the CSPROJ file and run the project.

History Remark

To understand the reason why Microsoft decided to introduce one more internet technology, we should look at history. In the beginning, there was SGML and then, based on it, HTML. HTML was used and is still being used as a great markup language for presenting data. When computers became faster and users needed more interaction with simple pages, a JavaScript (also called ECMAScript) was introduced. Web pages grew bigger and more complex and needed frequent updating, so such technologies as PHP, ASP and ASP.NET were born.

However, while web applications got richer, they needed more effort to support that richness. AJAX is the last approach used to make applications again more beautiful and powerful. Now lots of companies and developers are faced with the troubles that this power brings. It's hard to maintain large amounts of weakly typed JavaScript code. Not only that, but in every browser type your web application looks different, if it even works there at all. Furthermore, debugging a web application, especially if it is AJAX enabled, can become a real headache (but thanks for ASP.NET, it's a great pill for this headache).

All of these obstacles prevent companies and developers from creating really big and powerful web applications targeted for any-browser users. So, what will help us with this mess? Yeah, you are right: Silverlight will be our saver :).

Silver… What?

So, what is Silverlight? I'll try to explain it in a few words. Silverlight is a Microsoft technology that allows you to make rich applications with nice interfaces that are executed in a browser. "And what?" you'll probably ask. Well, first of all, it's truly cross-platform and cross-browser. This means that if you write your application using Silverlight, it will run in such browsers as IE, Firefox, Opera (coming soon) and Safari. Not only that, but wherever you run your application it will look the same.

The second benefit that we will achieve with Silverlight (version 1.1) is that applications can be written using any .NET language (!). You can write your application in C#, VB.NET or even Ruby or Python. No more JavaScript! However, if you like coding in JavaScript, you also can use Silverlight in version 1.1. Application design is based on a new markup language called XAML (pronounced "zammel"). Silverlight XAML is a subset of the WPF (Windows Presentation Foundation) XAML language. This means that once you've learned Silverlight, you can easily begin with WPF.

Versions

Today there are two known Silverlight versions: 1.0 and 1.1 Alpha Refresh. Version 1.0 is a start release that has XAML support and JavaScript for client-side coding. Version 1.1 is everything from 1.0 (this means programs that were written for 1.0 will run under Silverlight 1.1), plus .NET Framework. In these articles, I will target Silverlight 1.1 as the most interesting and exciting technology.

Development with Silverlight

The best way to learn something is to use it. First of all, you must download Silverlight itself. You can download Silverlight 1.1 Alpha from an official Silverlight page. Also, I recommend that you download and install Visual Studio 2008 Beta 2 and Microsoft Silverlight Tools Alpha for Visual Studio 2008 Beta 2. In this case, creating a Silverlight application will be as easy as creating a simple .NET application. However, if you somehow don't have the possibility of using VS 2008, it's possible to create a Silverlight application in VS 2005. Be aware that it is quite tricky, though, and against VS 2008 you won't have IntelliSense enabled for writing XAML files. I will describe the workaround of creating a Silverlight project in VS 2005 further on.

Using Visual Studio 2008 Beta 2

After installing VS 2008 Beta 2 on your machine, install Microsoft Silverlight Tools Alpha for Visual Studio 2008 Beta 2. This will add some project types to the New Project wizard and enable IntelliSense support for Silverlight XAML coding. Start Visual Studio and open a New Project wizard. Choose Silverlight Application under Visual C#. Enter the application name and click the OK button. After you've created a Silverlight Application project, you'll see in Solution Explorer the class library project with some files already added. We'll discuss them later. To check that everything works fine, change the content of the Page.xaml file by adding a TextBlock element inside a Canvas element. Your code will look like this:

XML
<Canvas ...>
    <TextBlock Text="Hello SilverWorld!" />
</Canvas>

Compile and run your project. If everything is right, you will see your first Silverlight Application. Great!

Hello World Silverlight application

Using Visual Studio 2005

If you are not lucky enough to have VS 2008 Beta 2, or just don't want to be so lucky, then you still have a chance at developing Silverlight 1.1 applications. Start Visual Studio 2005 and create an empty Class Library application. Remove all references from the project references and remove all files from the project. Go to project properties and then to the "Build" tab. Click on the "Advanced…" button and check "Do not reference mscorlib.dll."

Do not reference mscorlib.dll

After you've done that, add the following files, which are situated in the Silverlight installation directory (by default: C:\Program Files\Microsoft Silverlight), to the project's references: agclr.dll, mscorlib.dll, system.dll, System.Core.dll, System.Silverlight.dll, System.Xml.Core.dll. Then add files from any blank Silverlight project: TestPage.html, TestPage.html.js, Silverlight.js, Page.xaml, Page.xaml.cs (you can take them from the Silverlight SDK or from my samples). Here is Solution Explorer after completing these actions.

Visual Studio 2005 solution after adding references and moving files

Replace Page.xaml's content with the same code as in the VS 2008 section, but change the "x:Class" property of the Canvas element to bin/Debug/[Your Class Library Name].dll. Also remove the InitializeComponent() method call from Page.xaml.cs. Finally, compile the library, click the right mouse button on TestPage.html and choose "View in browser." Not an easy solution, but it should work. Note that Silverlight XAML support won't work (well it will, but not correctly), but IntelliSense for .NET development works fine and that's great. The reason why it works, you'll understand afterwards by digging a little bit deeper into Silverlight.

Inside a Nutshell

To write powerful Silverlight applications, we need to understand how it works inside. Let's add the following code to our Page.xaml and Page.xaml.cs files.

Page.xaml:

XML
<Canvas ...>
    <TextBlock x:Name="HelloBlock" Text="Click Me!"  
        OnClick="TextBlockClicked"/>
</Canvas>

Page.xaml.cs:

C#
...
public void TextBlockClicked(object sender, MouseEventArgs e)
{
    HelloBlock.Text = "Clicked!";
}
...

Compile our Silverlight project and run it. Click on TextBlock and you'll see that the text will be changed. Now let's see how it works.

When you build a Silverlight application, the same things happen as would in a simple class library. In fact, it is a class library. However, unlike a simple class library, it has references to other versions of mscorlib and other libraries. Those libraries are also simple .NET libraries. That is why we can use Visual Studio 2005 for Silverlight development even with .NET IntelliSense support: there is no difference between compiling common .NET applications and Silverlight applications. So, after building a project, we have a .NET library with application logic and a XAML file with its UI description. Note that XAML with a code-behind .NET class is something similar to an ASP.NET page with its code-behind file.

The next thing I should point out is how a Silverlight application is loaded by the client. Look at the TestPage.html page: there you'll see references to the Silverlight.js and TestPage.html.js script files. The only element in that page is <div> with the CreateSilverlight() function in it. This is the place where the creation of Silverlight applications takes place. When the page loads, the browser calls the CreateSilverlight() function, which is defined in the Default.html.js file. Let's have a look at this function:

JavaScript
//contains calls to silverlight.js, example below loads Page.xaml
function createSilverlight()
{
    Silverlight.createObjectEx(
    {
        source: "Page.xaml",
        parentElement: document.getElementById("SilverlightControlHost"),
        id: "SilverlightControl",
        properties: 
        {
            width: "100%",
            height: "100%",
            version: "1.1",
            enableHtmlAccess: "true"
        },
        events: {}
    });
       
    // Give the keyboard focus to the Silverlight control by default
    document.body.onload = function() 
    {
        var silverlightControl = 
            document.getElementById('SilverlightControl');
        if (silverlightControl)
        silverlightControl.focus();
    }
} 

It creates a Silverlight application with specified properties of XAML file, width, height, etc. This is the place where Silerlight.js code is used. Information about parameters passed to the Silverlight.createObjectEx() function can be found at the MSDN article Using CreateSilverlight.js and Silverlight.js. All it does is activate the browser's Silverlight ActiveX plug-in and run it with specified parameters. In this moment, "woo-hoo" takes place. Your library is loaded as a simple .NET assembly and Silverlight .NET runtime executes it. Everywhere. Yeah, this is the cross-platform .NET Framework. Microsoft placed the whole .NET Framework (of course, it has some limitations) in only 4 megabytes. That's awesome.

Coding Basics

The processes that take place in your Silverlight application (e.g. loading, event handling) are mostly the same as in Windows Forms applications. A basic Silverlight application consists of a XAML file and a code-behind file. This behavior is similar to the ASP.NET model, where we have an ASPX file with some HTML and ASP.NET elements, as well as a code-behind file with page logic. So, everything you define in XAML you can access from code-behind programmatically.

Let's have a look at XAML basics using the previous example. The root element is <Canvas>; it's a container for all objects in Silverlight and is itself a Silverlight object. This means that it can contain other canvas objects. A TextBlock is a simple control that has one function: to display text. Other properties are quite easy to understand. Currently, all elements in a Silverlight application are absolutely positioned and there are no controls like the stack panel in WPF. However, it's quite possible that such controls will be introduced in future beta versions of Silverlight. Also, there are no basic controls like buttons, textboxes and others. They will, of course, be in the final 1.1 release, but for now you can look at some examples of controls that are distributed with Silverlight SDK 1.1.

When it comes around to coding your Silverlight application in .NET, then it becomes very similar to Windows Forms or ASP.NET. You have some controls on your canvas and you can assign handlers for the different events of those controls. There a 2 ways to do that. The first is similar to Windows Forms in that you can use event properties of objects that represent some element from the canvas. For example:

C#
MyTextBlock.MouseLeftButtonDown += new MouseEventHandler(
    MyTextBlock_MouseLeftButtonDown);

The second way is similar to ASP.NET: you can add the attribute MouseLeftButtonDown to the element right in the XAML file. Its value passes the name of the function, which should be called when the event will be raised. Here is how it looks:

XAML file:

XML
<TextBlock MouseLeftButtonDown="clicked"/>

XAML.cs file:

C#
public void clicked(MouseEventArgs e)
{
    // Some code goes here
}

Some elements' properties can be accessed using object properties. Others can only be accessed using the function GetValue() and set using the SetValue() function. For example, an element's position can be set in the following way:

C#
Element.SetValue<double>(Canvas.Left, 100);

You can see that it will be really easy to learn programming with Silverlight if you are familiar with some basic principles of Windows Forms and/or ASP.NET application development.

Nice Sample

Ok, let's do something more interesting than hello world. Let it be a simple drawing application, like Paint, where it will be possible to draw on a surface using a brush. We will implement some basic functionality such as brush size and color. Let's start with those. We'll define 3 circles of different sizes in the bottom left corner of our surface to act as brush size selectors. We'll then define 3 rectangles with different colors in the right corner, which will act as brush color selectors. Here is the XAML code.

XML
<Canvas x:Name="parentCanvas"
    xmlns="http://schemas.microsoft.com/client/2007" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    Loaded="Page_Loaded" 
    x:Class="SilverPaint.Page;assembly=ClientBin/SilverPaint.dll"
    Width="640"
    Height="480"
    Background="White">
    <Canvas x:Name="Surface" Background="White" Canvas.Left="0" 
        Canvas.Top="0" Width="640" Height="430">
    </Canvas>    

    <Ellipse Canvas.Left="20" Canvas.Top="447" Width="6" Height="6" 
        MouseLeftButtonDown="SizeSelected">
        <Ellipse.Fill>
            <SolidColorBrush Color="Blue" />
        </Ellipse.Fill>
    </Ellipse>
    <Ellipse Canvas.Left="60" Canvas.Top="445" Width="10" Height="10" 
        MouseLeftButtonDown="SizeSelected">
        <Ellipse.Fill>
            <SolidColorBrush Color="Blue" />
        </Ellipse.Fill>
    </Ellipse>
    <Ellipse Canvas.Left="100" Canvas.Top="440" Width="20" 
        Height="20" MouseLeftButtonDown="SizeSelected">
        <Ellipse.Fill>
            <SolidColorBrush Color="Blue" />
        </Ellipse.Fill>
    </Ellipse>

    <Rectangle Canvas.Left="400" Canvas.Top="440" Width="50" 
        Height="20" MouseLeftButtonDown="ColorSelected">
        <Rectangle.Fill>
            <SolidColorBrush Color="Red" />
        </Rectangle.Fill>
    </Rectangle>
    <Rectangle Canvas.Left="460" Canvas.Top="440" Width="50" 
        Height="20" MouseLeftButtonDown="ColorSelected">
        <Rectangle.Fill>
            <SolidColorBrush Color="Green" />
        </Rectangle.Fill>
    </Rectangle>
    <Rectangle Canvas.Left="520" Canvas.Top="440" Width="50" 
        Height="20" MouseLeftButtonDown="ColorSelected">
        <Rectangle.Fill>
            <SolidColorBrush Color="Blue" />
        </Rectangle.Fill>
    </Rectangle>
</Canvas>

Under the root canvas first comes another Canvas element with the "x:Name" property equal to Surface. This is the place where we will draw using the brush. Then in the code-behind file we will use this Surface as an object name for accessing this canvas. Next, 3 ellipses are our circles for selecting brush size. I hope you'll understand all of their properties, but if not, just refer to Silverlight's documentation on MSDN as it's pretty clear. The one property you should look at is MouseLeftButtonDown, which is set to SizeSelected. This is the name of our handler for changing size.

Next, 3 rectangles are used for selecting color and their behaviour is similar to ellipses. Now look at the code-behind file, which implements all logic about changing brush color/size and drawing on the surface.

C#
using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Shapes;
using System.Windows.Media;

namespace SilverPaint
{
    public partial class Page : Canvas
    {
        private Point _prevMovingPosition; // Previous mouse position
        private Color _currentColor = Colors.Blue; // Current brush color
        private double _currentSize = 10; // Current brush Size

        private void DrawCircle(Point position)
        {
            Ellipse ellipse = new Ellipse();
            // We are filling our ellipse with solid brush 
            // with _currentColor color
            ellipse.Fill = new SolidColorBrush(_currentColor); 
            // Setting ellipse size
            ellipse.Width = _currentSize;
            ellipse.Height = _currentSize;
            // Setting ellipse position to make it center in position 
            ellipse.SetValue<double>(Canvas.LeftProperty, 
                position.X - _currentSize / 2);
            ellipse.SetValue<double>(Canvas.TopProperty, 
                position.Y - _currentSize / 2);
            // Drawinf ellipse on Surface canvas
            Surface.Children.Add(ellipse);
        }

        public void Page_Loaded(object o, EventArgs e)
        {
            // Required to initialize variables
            InitializeComponent();
            // Adding handler to make drawing possible
            Surface.MouseLeftButtonDown += new MouseEventHandler(
                Page_MouseLeftButtonDown);
        }

        void Page_MouseLeftButtonDown(object sender, MouseEventArgs e)
        {
            // Remebering previous position
            _prevMovingPosition = e.GetPosition(this);
            DrawCircle(_prevMovingPosition);
            // Adding handlers to make possible drawing 
            // when mouse button is down
            // and user moves mouse over surface
            Surface.MouseMove += new MouseEventHandler(Page_MouseMove);
            Surface.MouseLeftButtonUp += new MouseEventHandler(
                Page_MouseLeftButtonUp);
        }

        void Page_MouseLeftButtonUp(object sender, MouseEventArgs e)
        {
            // Drawing finished, remove unnecessary handlers
            Surface.MouseMove -= Page_MouseMove;
            Surface.MouseLeftButtonUp -= Page_MouseLeftButtonUp;
        }

        void Page_MouseMove(object sender, MouseEventArgs e)
        {
            // First drawing circle at new position
            Point currentPosition = e.GetPosition(this);
            DrawCircle(currentPosition);            
            // Then drawing line from previous to current position
            Line smoothingLine = new Line();
            // Making line solid and setting its color to _currentColor
            smoothingLine.Stroke = new SolidColorBrush(_currentColor);
            // Making line thikness equal to brush size
            smoothingLine.StrokeThickness = _currentSize;
            // Setting line coords
            smoothingLine.X1 = _prevMovingPosition.X;
            smoothingLine.Y1 = _prevMovingPosition.Y;
            smoothingLine.X2 = currentPosition.X;
            smoothingLine.Y2 = currentPosition.Y;
            // Drawing Line on Surface canvas
            Surface.Children.Add(smoothingLine);
            // Saving moving position
            _prevMovingPosition = currentPosition;
        }

        void SizeSelected(object sender, MouseEventArgs e)
        {
            // Getting width directly from sender
            _currentSize = ((Shape)sender).Width;
        }

        void ColorSelected(object sender, MouseEventArgs e)
        {
            // Getting color directly from sender's brush
            _currentColor = ((SolidColorBrush)((Shape)sender).Fill).Color;
        }
    }
}

The DrawCircle function draws an ellipse on the surface with equal height and width. The size and color of the circle are taken from _currentColor and _currentSize. The Page_Loaded function is the handler for the OnLoad event, which is executed when the application starts. There, we are adding a handler to Surface's MouseLeftButtonDown event.

When MouseLeftButtonDown occurs, a circle is drawn on the surface and handlers are created for the MouseMove and MouseLeftButtonUp events. So, when you are moving your mouse with a pressed button, a circle is being drawn on the new position. Also note that a line is added connecting the old position with the new position. This is done for your curve to be smoother. The SizeSelected and ColorSelected methods are used to change the size and color of your brush.

Now compile and run the application. Try to draw something. Here is my result :).

SilverPaint in action

If needed, this simple sample can be easily extended to real Paint (for example, different brush types, real color picker, etc). So, you can see that some nice applications can be created really fast and easily with Silverlight.

Conclusion

That's all for this part of Beginning Silverlight. I explained how Silverlight works inside and showed a way of creating some basic applications. In the next part, I'll describe how to create a nice game using Silverlight. We'll create custom controls and will place them in a separate Silverlight library. It will also be possible to play our game in full screen mode, as Silverlight brings us such functionality. I'll show you how to use Web Services in Silverlight applications, and believe me, it's really easy.

I hope this article was helpful for you :).

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Web Developer
Russian Federation Russian Federation
Currently I'm a student at Russia's Saint Petersburg State University. I am programming about 10 years already. My current interests is Silverlight, ASP.NET AJAX, WPF, SharePoint and other MS technologies.

My motto is work hard, have fun and don't notice any difference Smile | :)

Comments and Discussions

 
Questionproblem in beginning with silverlight Pin
vasu_g27-Mar-10 0:16
vasu_g27-Mar-10 0:16 
Generalgive me the same code for the vs 2005 Pin
JayPatel78629-Jan-09 19:49
JayPatel78629-Jan-09 19:49 
GeneralThanx! Pin
AdidasSG28-Jul-08 3:04
AdidasSG28-Jul-08 3:04 
GeneralRe: Thanx! Pin
Andrey Baskov8-Jul-08 3:16
Andrey Baskov8-Jul-08 3:16 
General[Message Removed] Pin
Mojtaba Vali14-May-08 0:17
Mojtaba Vali14-May-08 0:17 
GeneralWaiting for part 2 Pin
decyclone6-May-08 6:06
decyclone6-May-08 6:06 
GeneralRe: Waiting for part 2 Pin
Andrey Baskov3-Jun-08 1:36
Andrey Baskov3-Jun-08 1:36 
GeneralRe: Waiting for part 2 Pin
DYuvaraj7-Nov-09 6:05
DYuvaraj7-Nov-09 6:05 
Generalsilver light with visual C# express edition 2005 problem Pin
odinlai16-Jan-08 7:31
odinlai16-Jan-08 7:31 
GeneralRe: silver light with visual C# express edition 2005 problem Pin
Andrey Baskov23-Jan-08 6:35
Andrey Baskov23-Jan-08 6:35 
GeneralRe: silver light with visual C# express edition 2005 problem Pin
odinlai23-Jan-08 7:00
odinlai23-Jan-08 7:00 
GeneralRe: silver light with visual C# express edition 2005 problem Pin
yassir hannoun7-Feb-08 8:23
yassir hannoun7-Feb-08 8:23 
GeneralNice Peace Pin
dhanabalanr28-Dec-07 18:08
dhanabalanr28-Dec-07 18:08 
QuestionTrue or false? Pin
myshketer18-Nov-07 23:21
myshketer18-Nov-07 23:21 
AnswerRe: True or false? Pin
Andrey Baskov19-Nov-07 0:30
Andrey Baskov19-Nov-07 0:30 
GeneralRe: True or false? Pin
myshketer19-Nov-07 3:49
myshketer19-Nov-07 3:49 
GeneralRe: True or false? Pin
myshketer19-Nov-07 3:51
myshketer19-Nov-07 3:51 
GeneralRe: True or false? Pin
myshketer19-Nov-07 5:22
myshketer19-Nov-07 5:22 
QuestionQuestion... Pin
Relkin09-Nov-07 19:03
Relkin09-Nov-07 19:03 
GeneralRe: Question... Pin
Relkin09-Nov-07 19:37
Relkin09-Nov-07 19:37 
GeneralRe: Question... Pin
Andrey Baskov9-Nov-07 21:21
Andrey Baskov9-Nov-07 21:21 
Yeah, there is no such attribute OnClick. You have MouseLeftButtonUp and MouseLeftButtonDown in Silverlight for work with mouse buttons. Unfortunately, currently there is no documentation in MSDN about Silverlight 1.1 but I hope we'll have it with beta release of SL 1.1.

Best Regards,
Andrey Baskov

GeneralNice Article. Pin
rilov21-Oct-07 14:43
rilov21-Oct-07 14:43 
GeneralGood Article Pin
Andrey Altukhov18-Oct-07 14:31
Andrey Altukhov18-Oct-07 14:31 
QuestionSilverlight with c++ Pin
TimKoelewijn17-Oct-07 22:15
TimKoelewijn17-Oct-07 22:15 
AnswerRe: Silverlight with c++ Pin
Andrey Baskov17-Oct-07 22:39
Andrey Baskov17-Oct-07 22:39 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.