Dr. Dobb's is part of the Informa Tech Division of Informa PLC

This site is operated by a business or businesses owned by Informa PLC and all copyright resides with them. Informa PLC's registered office is 5 Howick Place, London SW1P 1WG. Registered in England and Wales. Number 8860726.

Channels ▼


Working with Events in Silverlight

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">
        <EventTrigger RoutedEvent="Canvas.Loaded">
                    <DoubleAnimation AutoReverse="True"  
                      From="80" To="200" Duration="0:0:3" 
    <Canvas Canvas.Left="10" Canvas.Top="10" Height="300" 
      Width="300" Background="#efefef">
	          <RotateTransform Angle="25"/>
		        <SkewTransform AngleX="25"/>
	  <Rectangle Name="Rect" Canvas.Top="25" Canvas.Left="25" 
	    Width="200" Height="150" Fill="Yellow" Loaded="ShowLoad" 
	    MouseEnter="MouseEnter" MouseLeave="MouseLeave"
	  <TextBlock Name="tbHello"
	    Canvas.Left="36" Canvas.Top="80"
	    Foreground="Maroon" FontFamily="Verdana" 
          FontSize="24" FontWeight="Bold"
	      Text="Hello From Silverlight!">
Listing One: Embedding events and event handler references into XAML code.

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




Called when the canvas object loads.


Called as the mouse enters an object's area.


Called as the mouse exits an object's area.


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.

Related Reading

More Insights

Currently we allow the following HTML tags in comments:

Single tags

These tags can be used alone and don't need an ending tag.

<br> Defines a single line break

<hr> Defines a horizontal line

Matching tags

These require an ending tag - e.g. <i>italic text</i>

<a> Defines an anchor

<b> Defines bold text

<big> Defines big text

<blockquote> Defines a long quotation

<caption> Defines a table caption

<cite> Defines a citation

<code> Defines computer code text

<em> Defines emphasized text

<fieldset> Defines a border around elements in a form

<h1> This is heading 1

<h2> This is heading 2

<h3> This is heading 3

<h4> This is heading 4

<h5> This is heading 5

<h6> This is heading 6

<i> Defines italic text

<p> Defines a paragraph

<pre> Defines preformatted text

<q> Defines a short quotation

<samp> Defines sample computer code text

<small> Defines small text

<span> Defines a section in a document

<s> Defines strikethrough text

<strike> Defines strikethrough text

<strong> Defines strong text

<sub> Defines subscripted text

<sup> Defines superscripted text

<u> Defines underlined text

Dr. Dobb's encourages readers to engage in spirited, healthy debate, including taking us to task. However, Dr. Dobb's moderates all comments posted to our site, and reserves the right to modify or remove any content that it determines to be derogatory, offensive, inflammatory, vulgar, irrelevant/off-topic, racist or obvious marketing or spam. Dr. Dobb's further reserves the right to disable the profile of any commenter participating in said activities.

Disqus Tips To upload an avatar photo, first complete your Disqus profile. | View the list of supported HTML tags you can use to style comments. | Please read our commenting policy.