Working with Events in Silverlight

A rich event-driven development model that can be used to detect when users perform specific actions


February 29, 2008
URL:http://www.drdobbs.com/web-development/working-with-events-in-silverlight/206901111

Dan Wahlin is a .NET development instructor and architecture consultant at Interface Technical Training. Dan founded the XML for ASP.NET Developers Web site, which focuses on using ASP.NET, XML, AJAX, and Web Services in Microsoft's .NET platform. Dan blogs at http://weblogs.asp.net/dwahlin and http://blogs.interfacett.com/dan-wahlins-blog.


It's no secret that today's applications require a high-level of interactivity between user actions and application code. It's critical for developers to know what actions a user performs so that they can call the appropriate code to show and hide content, hit a database or perform other tasks. Although each of today's more modern languages handles events differently, they all provide the ability to attach events to event handlers.

Silverlight 1.0 provides a rich event-driven development model that can be used to detect when users perform specific actions or when Silverlight objects complete various tasks or operations. This can be useful when users interact with objects on a Silverlight canvas, to detect a file's download progress or when you need to be notified that a canvas has loaded and is available to use. Silverlight events can be defined in XML Application Markup Language (XAML) files and handled using JavaScript. In this article, you'll see how to work with Silverlight events and see how they're similar in many ways to HTML events.

Comparing HTML Events and XAML Events

Working with events in Silverlight is quite similar to working with events in HTML. Events are defined using a declarative language (markup language) and handled using a programming language. HTML provides a simple way to embed events and event handler references into various elements contained within a page. For example, to handle a button's click event you could add the following code:

<input type="button" id="btnSubmit" value="Click Me" 
  onClick="btnSubmit_Click" />

JavaScript embedded in the HTML page (or stored externally) could then handle the event:

function btnSubmit_Click()
{
    var outputDiv = document.getElementById("divOutput");
    outputDiv.innerHTML = "You clicked the button!";
}

Although this is very simple example, the same overall concept applies to Silverlight applications. Events and their associated references are defined in XAML and handled using JavaScript. An example of embedding events into an XAML document is in Listing One.

<Canvas xmlns="http://schemas.microsoft.com/client/2007" Loaded="ShowLoad">
    <Canvas.Triggers>
        <EventTrigger RoutedEvent="Canvas.Loaded">
            <BeginStoryboard>
                <Storyboard>
                    <DoubleAnimation AutoReverse="True"  
                      From="80" To="200" Duration="0:0:3" 
                       Storyboard.TargetName="tbHello"
			     Storyboard.TargetProperty="(Canvas.Top)"
                       RepeatBehavior="Forever"/>
			</Storyboard>
               </BeginStoryboard>
        </EventTrigger>
    </Canvas.Triggers>
    <Canvas Canvas.Left="10" Canvas.Top="10" Height="300" 
      Width="300" Background="#efefef">
        <Canvas.RenderTransform>
            <TransformGroup>
	          <RotateTransform Angle="25"/>
		        <SkewTransform AngleX="25"/>
		</TransformGroup>
	  </Canvas.RenderTransform>
	  <Rectangle Name="Rect" Canvas.Top="25" Canvas.Left="25" 
	    Width="200" Height="150" Fill="Yellow" Loaded="ShowLoad" 
	    MouseEnter="MouseEnter" MouseLeave="MouseLeave"
	    MouseLeftButtonDown="MouseClick"/>
	  <TextBlock Name="tbHello"
	    Canvas.Left="36" Canvas.Top="80"
	    Foreground="Maroon" FontFamily="Verdana" 
          FontSize="24" FontWeight="Bold"
	      Text="Hello From Silverlight!">
	  </TextBlock>
    </Canvas>
</Canvas>
Listing One: Embedding events and event handler references into XAML code.

Table 1 summarizes the events defined in the XAML shown in Listing One.

Event

Description

Loaded

Called when the canvas object loads.

MouseEnter

Called as the mouse enters an object's area.

MouseLeave

Called as the mouse exits an object's area.

MouseLeftButtonDown

Called as the left mouse button is clicked on an object.

Table 1

The Loaded event defined on the root canvas notifies you when the canvas has loaded so that you know when to interact with it and its children. It's similar to the onLoad event that can be added to an HTML body tag. The XAML Canvas object exposes several other events as well such as GotFocus, KeyDown, KeyUp, LostFocus, MouseEnter, MouseLeave, MouseLeftButtonDown, MouseLeftButtonUp, and MouseMove.

When the canvas is loaded a JavaScript function named ShowLoad() is called. The ShowLoad() function is shown next:

var _Control = document.getElementById('slControl');
var _TB = null;        
function ShowLoad(sender,eventArgs)
{
   if (sender == "Canvas") _TB = _Control.Content.FindName("tbHello");
   alert("Object Loaded.  Sender = " + sender);
}

If you program in VB.NET or C#, the parameter signature on the ShowLoad() event handler should look familiar. When the event is raised the sender of the object is passed (the Canvas object) as well as event argument data. ShowLoad() checks to see if the sender is a Canvas object and then locates a TextBlock object named tbHello using the FindName() method.

The XAML in Listing One also defines several mouse events including MouseEnter, MouseLeave, and MouseLeftButtonDown. hese events fire as the user enters, leaves or clicks a Rectangle object defined in the Silverlight application. The Rectangle object also defines a Loaded event that calls the ShowLoad() method discussed earlier. The JavaScript code that handles the enter, leave and left button down events is in Listing Two. Looking through the code you'll see that all of the methods have the same parameter signature which allows for a consistent way to handle events and event data.

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!";
}
Listing Two: Handling different mouse events in Silverlight.

Silverlight 1.0 doesn't provide a built-in way to know when the right mouse button has been clicked unfortunately. Hopefully that functionality will make it into a future version of Silverlight.

In addition to the events in Listing One, you'll also find a special tag named EventTrigger that can be used to route events and perform actions defined in the XAML. In this example, EventTrigger handles the root Canvas object's Loaded event. It does this using the RoutedEvent attribute. As the Canvas object's Loaded event fires, the EventTrigger will play a storyboard animation that changes the TextBlock's Top property to move the TextBlock object up and down on the canvas. Because the animation's RepeatBehavior attribute is assigned a value of Forever, the animation will play until the application is closed.

Although a complete discussion of routed events is beyond the scope of this article, it's important to understand the overall role they play in XAML and how they can be used to route events to actions. You'll find additional details about event triggers and routed events in the Silverlight 1.0 SDK available at www.silverlight.net.

Using Events to Download Files

Silverlight events can also be used in other ways that don't involve require user interaction. In Silverlight you can use a built-in Downloader object to download files used by an application on-the-fly. This functionality is useful when you need to download several images as an application initializes or need to download XAML fragments or other file types on demand as a user performs an action.

The Silverlight Downloader object exposes three events as in Table 2.

Event

Description

Completed

Fires when a download completes.

DownloadFailed

Fires when a download fails due to no content being returned.

DownloadProgressChanged

Fires as a download progresses and provides the percentage of the file that has been downloaded.

Table 1

Listing Three provides an example of using the Silverlight Downloader object and handling its events. The code starts by creating the Silverlight object instance using the standard Silverlight.createObjectEx() method. Within this method the onLoad event is hooked to an event handler of the same name. The onLoad() event handler creates the Downloader control using the CreateObject() method and then wires its events to their respective event handlers using the AddEventListener() method. Once the events are wired up it then defines the file to download and calls Send() to start the download.

As the file is downloaded the onDownloadProgressChanged() event handler is called which is used to get the download progress. The code then updates a TextBlock object's Text property with the percentage of the download that has completed. When the file download completes the onCompleted() event handler is called which provides the user with an updated status.

var _TB = null;
function CreateSilverlight()
{
  Silverlight.createObjectEx(
    {
      source: "MyApp.xaml",
      parentElement: document.body,
      id: "slControl",
      properties: { width: "100%", height: "100%", version: "1.0" },
      events: { onLoad: onLoad, onError: null }
    }
  );
}
function onLoad(control, context, rootElement)
{
    _TB = control.Content.FindName("tbProgress");
    var downloader = control.CreateObject("downloader");
    downloader.AddEventListener("DownloadProgressChanged", 
     onDownloadProgressChanged);
    downloader.AddEventListener("Completed", onCompleted);
    downloader.AddEventListener("DownloadFailed", onDownloadFailed);
    downloader.Open("GET", "MyFiles.zip?" + new Date()); 
    downloader.Send();
}
function onDownloadProgressChanged(sender, eventArgs)
{
    var percentComplete = sender.DownloadProgress * 100;
    _TB.Text = Math.floor(percentComplete) + "%";
}
function onCompleted(sender, eventArgs)
{
    _TB.Text = "Download complete!";
    //Access files that were downloaded
}
Function onDownloadFailed(sender, eventArgs)
{
    //eventArgs will always be null in this event handler
    alert("Download failed");
}
Listing Three: Handling events exposed by Silverlight's Downloader object.

Conclusion

Events are where it's at in the world of application development. By defining events in XAML and handling them in JavaScript you can build a Silverlight application that is responsive to end user actions.

Terms of Service | Privacy Statement | Copyright © 2024 UBM Tech, All rights reserved.