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>
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. |
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!"; }
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.