Handling application-level events

Silverlight allows us to handle application-level events. They are the Startup, Exit, and UnhandledException events. These events can be used to hook into the application lifecycle. All of these events are found in the App.xaml.cs file.

The Application_Startup event is fired as soon as the application is initiated, meaning right after the XAP file is loaded to the user's computer and inspected by the Silverlight runtime engine. By default the Application_Startup event is used to load the default visual page into view. Other use of this event is to perform different initialization tasks, such as processing initialization parameters or setting application-wide resources or properties. For example, if you pass InitParams from the Silverlight HTML object to the application, you'll have to process them inside this event with code as follows:

IDictionary<string, string> iParams = e.InitParams;

The Application_UnhandledException event enables us to handle uncaught exceptions on the application level. Any exception that hasn't been caught by a try-catch block inside the application will be sent to this event. This is the last stop to handle the exception in a graceful way such as logging the error or displaying a message to the user. The event uses an argument, named e by default, of the ApplicationUnhandledExceptionEventArgs type to give you access to the exception that caused the event to fire. The default implementation of the event is as follows:

private void Application_UnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e)
{
if (!System.Diagnostics.Debugger.IsAttached)
{
e.Handled = true;
Deployment.Current.Dispatcher.BeginInvoke(delegate { ReportErrorToDOM(e); });
}
}

Notice the Handled property in the preceding code snippet. This Boolean property signals the framework whether the exception has been handled or not. By setting the Handled property to true, you signal the framework that the exception was handled and that it should continue to run. Leaving the property as false however, will cause the Silverlight plugin to unload the application and fire the OnError event.

Last, but not least, is the Application.Exit event. This is the last stop of an application before it shuts down into the oblivion. This event can be useful for tasks such as logging information or performing last-minute saves. The event is fired whenever a user leaves the application either by exiting it directly, closing the browser or having the Silverlight's object tag removed from the page with the help of JavaScript, for example.

The most important thing to remember about this event is that it fires after the browser is closed. Therefore, you cannot manipulate any UI visuals from this event or try to prevent the user from closing the browser.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.21.106.7