Welcome!

Silverlight Authors: Automic Blog, Michael Kopp, AppDynamics Blog, Kaazing Blog, Steven Mandel

Related Topics: Silverlight, Java IoT, Microsoft Cloud, Machine Learning

Silverlight: Article

Getting Started with Silverlight: Zero to Hero

What you need to do to get up and running with Silverlight quickly

Lots of people have been asking about how to get started with Silverlight, and what they need to do to get up and running with Silverlight quickly. Inspired by blog posts such as Jesse Liberty's, I'm going to take this from first principles, with no prior knowledge assumed.

Over the series, we'll look at the following:

  • Your First Silverlight Application
  • Understanding XAML
  • Understanding the Blend series of Products
  • Building Silverlight applications using Aptana on the Mac
  • Building Silverlight applications using Visual Studio Express on the PC
  • Programming Silverlight 1.0 with JavaScript
  • And whatever else you'd like -- send feedback!
So let's get started with the first and most simple application -- a 'Hello World' in Silverlight. You need no special tools for this. Just notepad will do...

Step 1. Silverlight.js
The first thing you'll need is Silverlight.js. This file contains everything that you need to create a silverlight component on your page. Silverlight is a browser plug-in that renders XAML and exposes a JavaScript programming interface. Browser plug-in's are implemented using special HTML tags called <object> and <embed>. Different browsers handle them differently, so instead of having to fiddle with them, it's a lot easier just to use Silverlight.js which handles it all for you.

You can get it here or in the Silverlight SDK, which installs to \PROGRAM FILES\Microsoft Silverlight 1.0 SDK. You'll find Silverlight.js in the 'Resources' directory.

Step 2. XAML
Silverlight UI is defined using XAML - XML Application Markup Language. Some great resources to get you started with XAML can be found in the Silverlight quickstarts here.

Our simple first application will be a XAML Canvas that contains a TextBlock control which, as its name suggests, renders text.

Here it is:

1: <Canvas
2:    xmlns="http://schemas.microsoft.com/client/2007"
3:    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
4:    Width="640" Height="480"
5:    Background="White"
6:    x:Name="Page">
7:    <TextBlock Width="195" Height="42" Canvas.Left="28" Canvas.Top="35"
8:       Text="Hello World!" TextWrapping="Wrap" x:Name="txt"/>
9: </Canvas>

Download it here.

This pretty simple piece of XAML contains two components.

The first is the root Canvas which is present in every Silverlight XAML. This defines the overall drawing surface. As you can see we are using a 640x480 Canvas which is white.

The second is the Textblock that we mentioned earlier. It renders the text 'Hello World' on the Canvas.

Remember XAML is just XML, so all of the conventions of XML apply. You can see that the TextBlock is a child node of the Canvas, and that XML attributes are used to define the properties of the nodes. Note that this is can empower some pretty cool scenarios -- such as generating UI on the fly from server applications using ASP.NET, PHP or Java. We'll look more into these scenarios later in the series.

Step 3. CreateSilverlight.js
The XAML document that you created in Step 2 should be saved and named. In this example use the name Page.xaml.

It's good practice to host the code for creating the Silverlight component on your page in a seperate JavaScript file. It's not essential, but for good clean separation of code to make maintenance easier, it's a useful step.

Typically we call this file CreateSilverlight.js, and I'm following that defacto standard here. You can download it from here.

1: function createSilverlight()
2: {
3:   Silverlight.createObjectEx({
4:     source: "Page.xaml",
5:     parentElement: document.getElementById("SilverlightControlHost"),
6:     id: "SilverlightControl",
7:     properties: {
8:       width: "100%",
9:       height: "100%",
10:       version: "1.0"
11:     },
12:     events: {
13:       onLoad: handleLoad
14:     }
15:   });
16: }

This function calls the 'createObjectEx' function which is implemented in Silverlight.js, which you added to your site in Step 1. You'll notice that a 'handleLoad' event has been defined. You'll see how this is implemented in Step 4.

Step 4. Your Application Logic
This simple application allows you to click on the text block, and have the text change from 'Hello World' to 'You Clicked Me'. The code for this application is shown here:

1: var SilverlightControl;
2: var theTextBlock;
3: function handleLoad(control, userContext, rootElement)
4: {
5:    SilverlightControl = control;
6:    theTextBlock = SilverlightControl.content.findName("txt");
7:    theTextBlock.addEventListener("MouseLeftButtonDown", "txtClicked");
8: }
9: function txtClicked(sender, args)
10: {
11:    theTextBlock.Text = "You clicked me!";
12: }

The handleLoad was defined as an event in the createSilverlight function. When Silverlight renders the control it calls this, passing it a reference to the control, the contents of the 'userContext' variable (which can be set in the createSilverlight), and a reference to the root canvas element.

This function finds the text block (called 'txt') and adds an event listener to it. The event that it is listening for is 'MouseLeftButtonDown', and when this happens the function called 'txtClicked' should be called.

When you implement an event handler, your function should accept parameters for 'sender' (the originator of the event) and 'args' (arguments associated with the event)

In this code you can see that when the user clicks the text block, the text will be changed to "You clicked me!"

Step 5. Your HTML Page
Now you put it all together with an HTML page that references each of the JavaScript files and embeds the Silverlight control. Here's the full HTML markup:

1: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3c.org/TR/1999/REC-html401-19991224/loose.dtd">
2: <html xmlns="http://www.w3.org/1999/xhtml">
3: <head>
4:   <title>ZeroHero</title>
5:
6:   <script type="text/javascript" src="Silverlight.js"></script>
1:
2:   <script type="text/javascript" src="CreateSilverlight.js">
1: </script>
2:   <script type="text/javascript" src="code.js">
1: </script>
2:   <style type="text/css">
3:     .silverlightHost {
4:       height: 480px;
5:       width: 640px;
6:     }
7:   </style>
8: </head>
9:
10: <body>
11:   <div id="SilverlightControlHost" class="silverlightHost">
12:     <script type="text/javascript">
13:       createSilverlight();
14:     </script>
7:   </div>
8: </body>
9: </html>

Upload all these files to your web server and you're done.

This might have seemed to be a lot just to get a 'Hello World' applicaiton, but it covers the full broad principles of developing a SIlverlight 1.0 application. You saw how to use Silverlight.js and createSilverlight.js, write XAML, load XAML into Silverlight, hook up events and create on-the-fly event handlers.

You can see the application in action here:

In the next part of this series, we'll look at Expression Blend, and how you can use it to design your XAML to make it richer!

More Stories By Laurence Moroney

Laurence Moroney is a senior Technology Evangelist at Microsoft and the author of 'Introducing Microsoft Silverlight' as well as several more books on .NET, J2EE, Web Services and Security. Prior to working for Microsoft, his career spanned many different domains, including interoperability and architecture for financial services systems, airports, casinos and professional sports.

Comments (3) View Comments

Share your thoughts on this story.

Add your comment
You must be signed in to add a comment. Sign-in | Register

In accordance with our Comment Policy, we encourage comments that are on topic, relevant and to-the-point. We will remove comments that include profanity, personal attacks, racial slurs, threats of violence, or other inappropriate material that violates our Terms and Conditions, and will block users who make repeated violations. We ask all readers to expect diversity of opinion and to treat one another with dignity and respect.


Most Recent Comments
Ellie's Professional Software Insight 02/18/08 11:14:41 PM EST

Trackback Added: Silverlight ????; ?? ?? ?? Silverlight? ??? ?????? ????? ???? ??

nbl 01/24/08 12:25:18 PM EST

What benefit does this give over using Javascript? Seems like the same amount of code.
some examples of getting started with Silverlight 1.1 please.

William Main 01/23/08 11:36:57 AM EST

I cannot get the silverlight to run on my server, which is at 1and1.com.

I have created a folder off of the root named scripts. Into this folder I have loaded the files

code.js
CreateSilverlight.js
helloworld.htm
page.xaml
Silverlight.js

I have modified the helloworld.htm file so that the scripts are loaded from /scripts for all of the js files.

I have also changed the CreateSilverlight.js file to load the source from the /scripts folder.

source: "/scripts/page.xaml"

There are no error messages. All I get is a blank web page. When I look at the source I get the following.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3c.org/TR/1999/REC-html401-19991224/loose.dtd">

ZeroHero

.silverlightHost {
height: 480px;
width: 640px;
}

createSilverlight();

Any ideas?

@ThingsExpo Stories
SYS-CON Events announced today that Taica will exhibit at the Japan External Trade Organization (JETRO) Pavilion at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Taica manufacturers Alpha-GEL brand silicone components and materials, which maintain outstanding performance over a wide temperature range -40C to +200C. For more information, visit http://www.taica.co.jp/english/.
SYS-CON Events announced today that SourceForge has been named “Media Sponsor” of SYS-CON's 21st International Cloud Expo, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. SourceForge is the largest, most trusted destination for Open Source Software development, collaboration, discovery and download on the web serving over 32 million viewers, 150 million downloads and over 460,000 active development projects each and every month.
Enterprises have taken advantage of IoT to achieve important revenue and cost advantages. What is less apparent is how incumbent enterprises operating at scale have, following success with IoT, built analytic, operations management and software development capabilities – ranging from autonomous vehicles to manageable robotics installations. They have embraced these capabilities as if they were Silicon Valley startups. As a result, many firms employ new business models that place enormous impor...
SYS-CON Events announced today that TidalScale will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. TidalScale is the leading provider of Software-Defined Servers that bring flexibility to modern data centers by right-sizing servers on the fly to fit any data set or workload. TidalScale’s award-winning inverse hypervisor technology combines multiple commodity servers (including their ass...
As popularity of the smart home is growing and continues to go mainstream, technological factors play a greater role. The IoT protocol houses the interoperability battery consumption, security, and configuration of a smart home device, and it can be difficult for companies to choose the right kind for their product. For both DIY and professionally installed smart homes, developers need to consider each of these elements for their product to be successful in the market and current smart homes.
SYS-CON Events announced today that MIRAI Inc. will exhibit at the Japan External Trade Organization (JETRO) Pavilion at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. MIRAI Inc. are IT consultants from the public sector whose mission is to solve social issues by technology and innovation and to create a meaningful future for people.
In his Opening Keynote at 21st Cloud Expo, John Considine, General Manager of IBM Cloud Infrastructure, will lead you through the exciting evolution of the cloud. He'll look at this major disruption from the perspective of technology, business models, and what this means for enterprises of all sizes. John Considine is General Manager of Cloud Infrastructure Services at IBM. In that role he is responsible for leading IBM’s public cloud infrastructure including strategy, development, and offering ...
As hybrid cloud becomes the de-facto standard mode of operation for most enterprises, new challenges arise on how to efficiently and economically share data across environments. In his session at 21st Cloud Expo, Dr. Allon Cohen, VP of Product at Elastifile, will explore new techniques and best practices that help enterprise IT benefit from the advantages of hybrid cloud environments by enabling data availability for both legacy enterprise and cloud-native mission critical applications. By rev...
SYS-CON Events announced today that NetApp has been named “Bronze Sponsor” of SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. NetApp is the data authority for hybrid cloud. NetApp provides a full range of hybrid cloud data services that simplify management of applications and data across cloud and on-premises environments to accelerate digital transformation. Together with their partners, NetApp emp...
SYS-CON Events announced today that Dasher Technologies will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 - Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Dasher Technologies, Inc. ® is a premier IT solution provider that delivers expert technical resources along with trusted account executives to architect and deliver complete IT solutions and services to help our clients execute their goals, plans and objectives. Since 1999, we'v...
SYS-CON Events announced today that TidalScale, a leading provider of systems and services, will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 - Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. TidalScale has been involved in shaping the computing landscape. They've designed, developed and deployed some of the most important and successful systems and services in the history of the computing industry - internet, Ethernet, operating s...
SYS-CON Events announced today that Massive Networks, that helps your business operate seamlessly with fast, reliable, and secure internet and network solutions, has been named "Exhibitor" of SYS-CON's 21st International Cloud Expo ®, which will take place on Oct 31 - Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. As a premier telecommunications provider, Massive Networks is headquartered out of Louisville, Colorado. With years of experience under their belt, their team of...
Widespread fragmentation is stalling the growth of the IIoT and making it difficult for partners to work together. The number of software platforms, apps, hardware and connectivity standards is creating paralysis among businesses that are afraid of being locked into a solution. EdgeX Foundry is unifying the community around a common IoT edge framework and an ecosystem of interoperable components.
Join IBM November 1 at 21st Cloud Expo at the Santa Clara Convention Center in Santa Clara, CA, and learn how IBM Watson can bring cognitive services and AI to intelligent, unmanned systems. Cognitive analysis impacts today’s systems with unparalleled ability that were previously available only to manned, back-end operations. Thanks to cloud processing, IBM Watson can bring cognitive services and AI to intelligent, unmanned systems. Imagine a robot vacuum that becomes your personal assistant tha...
Infoblox delivers Actionable Network Intelligence to enterprise, government, and service provider customers around the world. They are the industry leader in DNS, DHCP, and IP address management, the category known as DDI. We empower thousands of organizations to control and secure their networks from the core-enabling them to increase efficiency and visibility, improve customer service, and meet compliance requirements.
SYS-CON Events announced today that IBM has been named “Diamond Sponsor” of SYS-CON's 21st Cloud Expo, which will take place on October 31 through November 2nd 2017 at the Santa Clara Convention Center in Santa Clara, California.
Amazon is pursuing new markets and disrupting industries at an incredible pace. Almost every industry seems to be in its crosshairs. Companies and industries that once thought they were safe are now worried about being “Amazoned.”. The new watch word should be “Be afraid. Be very afraid.” In his session 21st Cloud Expo, Chris Kocher, a co-founder of Grey Heron, will address questions such as: What new areas is Amazon disrupting? How are they doing this? Where are they likely to go? What are th...
In a recent survey, Sumo Logic surveyed 1,500 customers who employ cloud services such as Amazon Web Services (AWS), Microsoft Azure, and Google Cloud Platform (GCP). According to the survey, a quarter of the respondents have already deployed Docker containers and nearly as many (23 percent) are employing the AWS Lambda serverless computing framework. It’s clear: serverless is here to stay. The adoption does come with some needed changes, within both application development and operations. Tha...
SYS-CON Events announced today that Avere Systems, a leading provider of enterprise storage for the hybrid cloud, will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 - Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Avere delivers a more modern architectural approach to storage that doesn't require the overprovisioning of storage capacity to achieve performance, overspending on expensive storage media for inactive data or the overbui...
SYS-CON Events announced today that N3N will exhibit at SYS-CON's @ThingsExpo, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. N3N’s solutions increase the effectiveness of operations and control centers, increase the value of IoT investments, and facilitate real-time operational decision making. N3N enables operations teams with a four dimensional digital “big board” that consolidates real-time live video feeds alongside IoT sensor data a...