Silverlight Events
Silverlight Events
Microsoft Silverlight provides a set of events that enable you to respond to actions, such as changes in Silverlight state and user input.
This topic contains the following sections:
- The Silverlight 1.0 Event Model
- Adding an Event Handler
- Defining an Event Handler
- Adding Event Handlers in JavaScript
- JavaScript Events
- Bubbled Events
- Error Events
For information about mouse and keyboard events, see Silverlight Mouse Support and Silverlight Keyboard Support.
The Silverlight 1.0 Event Model
In Silverlight 1.0, there are two general event cases: input events, and non-input events. Because Silverlight is built to work within the plug-in architecture of the hosting browser, the input stimulus for the input events is initially handled by the browser. The event is then sent to the Silverlight plug-in and is raised as an event in the Silverlight object model. Some events can only be handled on the plug-in instance itself, for instance the OnError event. Other events can only be handled on the root element of the XAML content, for instance the GotFocus event. Check the description or remarks for each event to determine the event handling scope.
The non-input events typically will report a state change to a particular object. Many of these state change events report the asynchronous download state or progress of the Downloader object, either directly on Downloader or through related APIs on image or media elements. The MediaElement also has a number of events that are exposed so that you can create transport controls for the media.
Silverlight provides events for the event types listed in the following table.
Event type | Events |
---|---|
Plug-in support and object lifetime | OnError OnFullScreenChange OnLoad OnResize Loaded (on UIElement) |
Downloader support | Completed (Downloader) DownloadProgressChanged (Downloader) |
Focus | GotFocus LostFocus |
Image and ImageBrush | ImageFailed (Image) ImageFailed (ImageBrush) DownloadProgressChanged (Image) DownloadProgressChanged (ImageBrush) |
Keyboard input | KeyDown KeyUp |
Media | BufferingProgressChanged Completed (Storyboard) CurrentStateChanged DownloadProgressChanged (MediaElement) MarkerReached MediaEnded MediaFailed MediaOpened |
Mouse input | MouseEnter MouseLeave MouseLeftButtonDown MouseLeftButtonUp MouseMove |
Adding an Event Handler
The following XAML example shows how to add a handler for the Loaded event on a Canvas object. Notice that the event-handler function cannot be called with parameter values (even empty ones), which is unlike JavaScript event-handler functions. Also notice that the event-handler function name is not prefixed with the string "javascript:". The "javascript:" prefix was accepted in prerelease versions of Silverlight, but it is not permitted in the current versions.
XAML |
---|
<Canvas xmlns="https://schemas.microsoft.com/client/2007" Loaded="onLoaded" /> |
Defining an Event Handler
The basic Silverlight event-handler function prototype contains two parameters, as described in the following table.
Parameter | Description |
---|---|
sender | Identifies the Silverlight object that generated the event. You can retrieve information about the object by calling the ToString method on the parameter value, or by checking specific properties of the object. |
eventArgs | Identifies the set of event data for a specific event. The event data often contains information about that particular occurrence of the event, which is the event being handled. Some events, such as the Loaded event, do not define any event data. In such cases, the value of eventArgs is null. The event data type, including whether it is always null, will be noted on the reference pages for each Silverlight event. |
Note If the Silverlight event-handler function does not reference the sender and eventArgs parameters, you do not have to define them as part of the function declaration.
The following JavaScript example shows how to define a Silverlight event-handler function. In this case, the code displays a string in an alert dialog box that contains the object type of the sender parameter.
JavaScript |
---|
function onLoaded(sender, eventArgs) { // Display the object type of the sender parameter. alert("Sender = " + sender.toString()); } |
You can reference named Silverlight objects other than the sender in an event-handler function. To name the object so that you can reference it later in script, use the x:Name attribute to specify an object's name in the object model. Then, typically by using the provided sender as the entry point into the general Silverlight object model, you can call FindName and reference the named object.
XAML |
---|
<Canvas xmlns="https://schemas.microsoft.com/client/2007" xmlns:x="https://schemas.microsoft.com/winfx/2006/xaml" Loaded="onLoaded"> <TextBlock x:Name="myTextBlock" /> </Canvas> |
The following JavaScript example shows how to use the FindName method to search the Silverlight object tree for a specific named object. In this case, the code displays the current date as the Text property of the TextBlock object.
JavaScript |
---|
function onLoaded(sender, eventArgs) { // Set the TextBlock to display the current date and time. sender.findName("myTextBlock").text = Date(); } |
The previous JavaScript example combines two separate operations in a single line of code. If you want to set multiple properties of a referenced object, you can create an object variable to hold the return value from the findName method, as shown in the following example.
JavaScript |
---|
function onLoaded(sender, eventArgs) { // Set the TextBlock to display the current date and time, and set the FontFamily and FontSize properties. var textblock = sender.findName("myTextBlock"); textblock.Text = Date(); textblock.FontFamily = "Comic Sans MS"; textblock.FontSize = "24"; } |
Using Specialized Event Data
For some events, the event data in eventArgs is as important as knowing that the event was raised. This is particularly true of the input events. For mouse events, the position of the mouse when the event occurred might be important. For keyboard events, keys on the keyboard raise the same KeyUp and KeyDown events, so in order to determine which key was pressed you must access the KeyboardEventArgs that are available to the event handler. It is a good practice to use more specific naming of the second parameter of event handler functions whenever a specialized set of event data is available for that event. For this example, the handler definition might use keyboardEventArgs instead of the less specific eventArgs. The event data type as well as properties within it that are available to a handler for a Silverlight event are noted in the reference for each event.
Adding Event Handlers in JavaScript
To add and remove event-handler functions in JavaScript, use the AddEventListener and RemoveEventListener methods. The following JavaScript example shows how to add events to a TextBlock object.
JavaScript |
---|
function onLoaded(sender, eventArgs) { textBlock = sender.findName("Status"); var entertoken1 = textBlock.addEventListener("MouseEnter", onMouseEnter); var leavetoken1 = textBlock.addEventListener("MouseLeave", onMouseLeave); } |
In some circumstances, you might want to remove event handlers. You might do this if you intend to replace a previously added event handler with a different handling function. To remove an existing event-handler function, use the RemoveEventListener method. The following JavaScript example shows how to remove event handler for two different events from a TextBlock object.
JavaScript |
---|
function removeEvents() { textBlock.removeEventListener("MouseEnter", entertoken1); textBlock.removeEventListener("MouseLeave", leavetoken1); } |
Notice how the remove event handler code references the named tokens that were declared as variables in the add event handler code. The tokens are really just integer values. The tokens are returned by the AddEventListener calls because it might be necessary to differentiate handlers if there was more than one handler defined for the same event on the same instance. If you do not intend to remove handlers later, you do not have to store the return value tokens when you call AddEventListener.
You can also remove handlers for cases where the event was added through a XAML attribute. In the XAML attribute case, there was no function call that could return a token. However, you can supply the value 0 (zero) for the token parameter to remove an event where the handler was added using a XAML attribute. The tokens represent the order that handlers were added, starting from 0 and counting up. Because the XAML attribute handlers are the first handlers added (parsing of XAML happens before any script can add handlers in Silverlight 1.0), and because there can only be one event handler added per event/instance using XAML, a XAML-added event handler's token value is always 0.
Capturing Input Events by Capturing the Mouse
You can use the CaptureMouse and ReleaseMouseCapture methods to enable and disable mouse capture. When an object has captured the mouse, it receives mouse input regardless of whether the cursor is within its borders. The mouse is typically captured only during drag operations. For more information about capturing the mouse, see the "Implementing Drag-and-Drop Functionality" section in Silverlight Mouse Support.
JavaScript Events
JavaScript provides a set of events that you can use to respond to changes on the Web page. For example, the following HTML example shows JavaScript code that is triggered by the JavaScript onload event.
JavaScript |
---|
<body onload='javascript:alert("onload event generated")'> |
In this example, JavaScript code is used directly instead of referencing an event-handler function. This is not possible with Silverlight events. By definition, the JavaScript onload event is not fired until the entire Web page is loaded. This means that any Silverlight plug-in contained within the page fires its Loaded event before the JavaScript onload event.
Bubbled Events
Silverlight supports the concept of a bubbled event for the following mouse input events:
A bubbled event is an event that is passed from a child object and is forwarded up to each of its successive parent elements in the object hierarchy. The object hierarchy is approximated by the XAML structure that is used to declare objects. The true object hierarchy might vary somewhat from the XAML because the object hierarchy does not include XAML language features such as property element tags, but in general you can think of the events as bubbling from XAML object element children towards the parent element that contains them, and doing so continuously until the root element is reached. For more information about bubbled events, see the "Event Bubbling" section in Silverlight Mouse Support.
Error Events
Errors in Silverkught can often be uniquely handled by writing a handler for the OnError event that is defined by the Silverlight plug-in object model. Error events always include event data in the form of ErrorEventArgs that are available to the error handler, and parser and runtime events provide the specialized subclasses ParserErrorEventArgs or RuntimeErrorEventArgs respectively. Writing error event handlers is discussed in more detail in the topic Silverlight Application Scripting Error Handling.
See Also
Silverlight Mouse Support
Silverlight Keyboard Support
Silverlight Object Models and Scripting to the Silverlight Plug-in
Silverlight Error Handling
Overviews and How-to Topics