Head Toward the Light

Getting Started with Silverlight 1.0

CoverStory

LANGUAGES: XAML | JavaScript | C#

ASP.NET VERSIONS: 3.5

 

Head Toward the Light

Getting Started with Silverlight 1.0

 

By Dan Wahlin

 

The overall acceptance of AJAX and Flash technologies in Web applications has led to the creation of more and more rich applications that provide an enhanced next generation user experience. End users are accustomed to visiting Web sites that show advertisements and media clips with Flash and load dynamic content with AJAX. With the release of Silverlight 1.0, Microsoft has thrown their hat into the rich Web experience ring and provided a nice foundation for developers to build upon. Silverlight works on Windows and Mac operating systems, and in multiple browsers, including Internet Explorer, FireFox, and Safari.

 

If you ve heard about Silverlight, but haven t yet had a chance to experiment with it, it s a browser plug-in that can play audio and video, perform animations and transformations, and enhance the way data is displayed in a Web page. You can download the plug-in and associated software development kit (SDK) and view many eye-catching Silverlight demos at http://silverlight.net.

 

Silverlight 1.0 is all about a declarative language named XML Application Markup Language (XAML), as well as JavaScript. It can also leverage various AJAX frameworks, including ASP.NET AJAX, to obtain data dynamically. Many demos focus on how audio and video can be added to Silverlight applications because it s very good at these types of tasks. But Silverlight can be used in many other scenarios, from games to data display. In this article, I ll provide an introduction to various features available in Silverlight 1.0, and describe the different pieces needed to make Silverlight work. Let s get started by looking at the overall architecture of Silverlight 1.0.

 

Putting the Pieces Together

Silverlight has several key technology players that are needed to make things work in a Web page. First, XAML is used to define the content displayed by Silverlight. XAML is an XML-based mark-up language that also is used by Windows Presentation Foundation (WPF). The version of XAML available in Silverlight 1.0 contains a sub-set of the overall XAML specification, as the Silverlight plug-in needs to stay small to allow for quick downloads and installations. Using XAML, you can define shapes, such as rectangles and ellipses, embed .wmv and .wma media files, perform snazzy animations to move objects around, and transform objects to perform interesting effects. I ll provide an introduction to XAML in the next section of the article.

 

In addition to XAML, Silverlight 1.0 relies on JavaScript to create a Silverlight control instance at run time, and to programmatically access various objects and media defined in XAML. In cases where you need to dynamically add content to Silverlight, you can use JavaScript to perform asynchronous operations (AJAX operations) without reloading the entire Web page. Any AJAX framework can be used, from Prototype to ASP.NET AJAX, to retrieve data and inject it into Silverlight.

 

Figure 1 shows the overall Silverlight architecture as defined in the Silverlight 1.0 SDK. You ll see that it provides support for decoding media, working with events, rendering content and text, parsing XAML, downloading objects used by Silverlight, performing animations, plus more.

 


Figure 1: The architecture of Silverlight 1.0.

 

Now that you ve seen the main Silverlight components, let s see how they work together. The basic steps to use Silverlight in a Web page are shown here:

1)     Create a new Web site in Visual Studio or Web Developer Express.

2)     Add the Silverlight.js file to the Web site.

3)     Create an XAML file that Silverlight will consume.

4)     Add a Web page with a

container that will hold the Silverlight control.

5)     Add a custom CreateSilverlight.js file to the site.

6)     Call Silverlight.createObject or Silverlight.createObjectEx within CreateSilverlight.js to create a Silverlight instance at run time.

7)     Reference the Silverlight.js and CreateSilverlight.js files in the Web page using the

   

 

   

       

           

          

       

       

   

Figure 2: Referencing the Silverlight.js and CreateSilverlight.js files and defining a container div.

 

function CreateSilverlight()

{

 Silverlight.createObjectEx(

     {

         source:'XAML/Basic.xaml',

   parentElement: document.getElementById('divSilverlight'),

   id: 'slControl',

   properties: {

     width: '500',

     height: '500',

     background:'#ffffffff',

             isWindowless: 'false',

     version: '1.0'

   },

   events: {

     onError: null,

     onLoad: null

   }, 

   context: null

    }

    );

}

Figure 3: Using the Silverlight.createObjectEx method to define the location of the XAML file and instantiate the Silverlight control with a specified height, width, background color, and version.

 

Getting Started with XAML

XML Application Markup Language (XAML) is a declarative language used to define shapes and text, define events, embed media, and perform animations and transformations. Silverlight applications are typically separated into one or more canvases using a Canvas element, much like Web pages are divided up using div elements. In fact, you can use a Silverlight canvas in similar scenarios where you d use a div in HTML.

 

Every Silverlight XAML file starts with a root Canvas element that defines a default namespace of http://schemas.microsoft.com/client/2007 (you may see an older version of the namespace in some Silverlight samples, as well). Child elements needed by the application are then placed within this root Canvas element. Figure 4 shows an example of an XAML canvas that contains a nested child canvas, along with other elements.

 

 

  Height="300" Width="300" Background="#efefef">

    

     Width="200" Height="150" Fill="Yellow" />

   

    Foreground="Maroon" FontFamily="Verdana" FontSize="24"

     FontWeight="Bold" Text="Hello, From Silverlight!">

   

 

Figure 4: Defining a canvas in XAML.

 

Looking through the XAML code, you ll see that Canvas elements can contain children. For example, the second Canvas element contains Rectangle and TextBlock child elements.

 

The second Canvas element defines where it should be displayed within its containing parent Canvas by using the Canvas.Left and Canvas.Top attributes (referred to as attached properties ). In this case, the child Canvas should be displayed 10 pixels from the left of the parent Canvas and 10 pixels down from the top. Likewise, the Rectangle and TextBlock elements also define where they should be displayed relative to their containing Canvas using the same attributes. In addition to positioning information, the Rectangle also defines its name, height, width, and background color. The TextBlock defines its name, foreground text color, font family, font size, font weight, and text using the appropriate attributes. Figure 5 shows an example of the output generated.

 


Figure 5: Output generated from running the XAML shown in Figure 4.

 

Figure 6 shows another example of an XAML file that defines different types of shapes, including a Rectangle, Ellipse, and Line. The output generated by this XAML when it s loaded and run by a Silverlight control is shown in Figure 7.

 

 

  Width="200" Height="150" Fill="Yellow" />

 

  Canvas.Left="10" Canvas.Top="20" Stroke="Black"

  StrokeThickness="3" Fill="Blue"/>

 

  Stroke="Black" StrokeThickness="5"/> 

 

  Canvas.Left="36" Canvas.Top="80"

  Foreground="Maroon" FontFamily="Verdana" FontSize="24"

  FontWeight="Bold" Text="Hello From Silverlight!">

 

Figure 6: Defining shapes using XAML elements.

 


Figure 7: Output generated by the XAML code shown in Figure 6.

 

XAML also provides a way to define audio or video within a Silverlight canvas. Supported media types include MP3, WMA, and WMV. Adding media to a Silverlight application is accomplished by using the MediaElement tag. MediaElement defines the source of the media, as well as how it should fill its container (in cases where video is being displayed). This is done using the Source and Stretch attributes, respectively. The Stretch attribute accepts the values shown in Figure 8.

 

Value

Description

Fill

The media content is resized to fill the container s dimensions. The aspect ratio isn t preserved when using this value.

None

The media content is shown in its default size.

Uniform

The media content is resized to fill the container s dimensions, but the original aspect ratio is preserved.

UniformToFill

The media content is resized to fill the container s dimensions, but the original aspect ratio is preserved. The source content is clipped to fit in the destination dimensions if the aspect ratio of the destination rectangle differs from the source.

Figure 8: Values accepted by the Stretch attribute.

 

Figure 9 shows an example of using the MediaElement tag to embed a .wmv file in a canvas. Because the MediaElement s AutoPlay attribute is set to True, the video will automatically start playing once the Silverlight canvas has loaded and the video file has buffered enough frames into memory. End users can also interact with media files through events to start, stop, and pause media. I ll provide an introduction to handling XAML events later in this article.

 

 

   Height="396.5" Canvas.Left="8" Canvas.Top="8"

   Source="Video/Sandwich_Thief.wmv" Stretch="Fill">

 

Figure 9: Adding media to a Silverlight canvas using the MediaElement tag.

 

Although discussing each of the elements and attributes available in the Silverlight XAML specification is outside the scope of this article, the Silverlight 1.0 SDK provides excellent coverage and, in many cases, provides examples of using them. You ll also find additional details about XAML at http://silverlight.net and on my blog (http://weblogs.asp.net/dwahlin).

 

Tools such as Microsoft s Expression Blend 2 can greatly simplify the process of creating XAML code and are recommended when working with large amounts of XAML. You can find out more about Expression Blend 2 at http://www.microsoft.com/expression/products/overview.aspx?key=blend.

 

Interacting with XAML Objects

Aside from look and feel, XAML also allows events and event handlers to be defined so that end users can interact with objects defined in a Silverlight canvas. Events are defined in a similar manner to HTML element events: they re placed directly on the target element. Figure 10 shows an example of defining different events and their associated event handler functions. The JavaScript event handler functions are typically placed in an external JavaScript file, but can be embedded directly in the page (as shown in Figure 11).

 

 Loaded="ShowLoad">

 

   Width="300" Background="#efefef">

     

      Width="200" Height="150" Fill="Yellow"

      Loaded="ShowLoad"

      MouseEnter="MouseEnter"

      MouseLeave="MouseLeave"

      MouseLeftButtonDown="MouseClick"/>

     

      Foreground="Maroon" FontFamily="Verdana" FontSize="24"

      FontWeight="Bold" Text="Hello from Silverlight!">

     

 

Figure 10: Adding events and event handler references to XAML.

 

var _TB = null;

function ShowLoad(sender,eventArgs)

{

 //Find Silverlight control in page

 //"slControl" defined in the createObjectEx() function call

 var slControl = document.getElementById('slControl');

 //Find TextBlock XAML element

 if (sender == "Canvas") _TB = slControl.Content.FindName("tbHello");

 alert("Object Loaded.  Sender = " + sender);

}

function MouseEnter(sender,eventArgs)

{

 _TB.Text = "Mouse entered " + sender;

}

function MouseLeave(sender,eventArgs)

{

 _TB.Text = "Mouse left " + sender;

}

function MouseClick(sender,eventArgs)

{

 _TB.Text = sender + " clicked!";

}

Figure 11: Defining event handlers using JavaScript.

 

The root Canvas element defined in Figure 10 defines a Loaded event and routes it to a JavaScript function named ShowLoad. This function will be called after all the Canvas children have been loaded and are ready to be used. The Rectangle element defined in the XAML defines three events (MouseEnter, MouseLeave, and MouseLeftButtonDown) and routes them to their respective event handlers. The event handlers (refer to Figure 11) dynamically change the Text property of the TextBlock defined in the XAML.

 

Note that the sender of the event, as well as event arguments, are passed to each function, which is similar to event data passed to VB.NET and C# event handlers. Looking through the code in Figure 11 you ll notice that XAML elements such as the TextBlock shown in Figure 10 are located using a FindName function. While HTML DOM elements can still be located using the document.getElementById function, XAML elements that have a defined Name attribute are always located using the Silverlight FindName function.

 

Media, shapes, text, and more can also be animated and transformed using XAML elements combined with events and triggers. Animations provide a way to add rich interactivity into an application that would be difficult to achieve using only HTML, CSS, and JavaScript. Silverlight has a built-in animation engine that can perform many animation tasks.

 

Different types of animations are available, ranging from generic animations that target an XAML element property to more fine-grained animations that target elements based on key frames and times. Multiple articles could be written on the subject of animations, so I ll simply introduce them with an example that demonstrates how to move a TextBlock object.

 

Figure 12 shows an example of using the Storyboard and DoubleAnimation XAML elements to target a TextBlock element s Canvas.Left property and perform an animation. When the root Canvas loads, the Loaded event will be handled which triggers an animation story board to play. The story board contains a DoubleAnimation element that changes the TextBlock s Canvas.Left property from 80 to 200 over a period of 3 seconds. Once the value of 200 is reached, the animation reverses and goes the other way. This is handled automatically by setting the AutoReverse property to True.

 

 

         

       

           

               

                From="80" To="200" Duration="0:0:3"

                Storyboard.TargetName="tbHello"

                Storyboard.TargetProperty="(Canvas.Left)"

                RepeatBehavior="Forever"/>

           

       

   

 

 

   Height="300" Width="300" Background="#efefef">

   

      Width="200" Height="150" Fill="Yellow" />

   

      Canvas.Left="36" Canvas.Top="80"

      Foreground="Maroon" FontFamily="Verdana"

      FontSize="24" FontWeight="Bold"

      Text="Hello From Silverlight!">

   

 

Figure 12: Using the Storyboard and DoubleAnimation elements to animate text on a Silverlight canvas.

 

Conclusion

Learning to build Silverlight applications is a lot like learning to build HTML applications. Once you understand which XAML elements and attributes can be used, you can perform more easily the tasks you need. This article has introduced many of the key concepts needed to get started with building Silverlight applications. You ve seen the major players required to instantiate and embed a Silverlight control in a Web page. You ve also seen how a canvas can be defined, as well as different types of children (such as Rectangle, Ellipse, and TextBlock). Finally, you ve seen how XAML object events can be handled using JavaScript, and how animations can be used to move XAML objects around a canvas.

 

In future articles, I ll walk through the process of creating a more robust Silverlight application that can integrate with ASP.NET AJAX and Web services to display remote data in a simulated 3D environment. Until then, you can see an example of the application in Figure 13, or download the application s code from http://www.xmlforasp.net/CodeSection.aspx?csID=129 to get a sneak peek. A video walk-through of the application can also be viewed at http://weblogs.asp.net/dwahlin/archive/2008/01/20/new-video-integrating-silverlight-and-asp-net-ajax.aspx.

 


Figure 13: A Silverlight application that leverages technologies, including ASP.NET AJAX and Web services.

 

The source code accompanying this article is available for download.

 

Dan Wahlin (Microsoft Most Valuable Professional for ASP.NET and XML Web services) is a .NET development instructor at Interface Technical Training (http://www.interfacetraining.com). Dan founded the XML for ASP.NET Developers Web site (http://www.XMLforASP.NET), which focuses on using XML, ADO.NET, ASP.NET, AJAX, and Web services in Microsoft s .NET platform. He s also on the INETA Speaker s Bureau and speaks at several conferences. Dan co-authored/authored several books on .NET, including ASP.NET 2.0 MVP Hacks (Wrox), Professional ASP.NET AJAX (Wrox), and XML for ASP.NET Developers (SAMS). When he s not writing code, articles, or books, Dan enjoys writing and recording music and playing golf and basketball with his wife and kids. Dan blogs at http://weblogs.asp.net/dwahlin and http://blogs.interfacett.com/dan-wahlins-blog.

 

 

 

Hide comments

Comments

  • Allowed HTML tags: <em> <strong> <blockquote> <br> <p>

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.
Publish