Monday, 3 March 2008

Silverlight 2 - App.Xaml Events

In Silverlight 2, we have the new App.Xaml file which we can use to store application resources (styles etc), that can be used throughout our Silverlight application.

For an example of using styles within the app.xaml file in Silverlight2, see scott guthries blog posting

The app.xaml.cs file also acts a little like a Global.asx file (for developers). An example of the app.xaml.cs file is below:

public partial class App : Application

public App()
this.Startup += this.Application_Startup;
this.Exit += this.Application_Exit;
this.UnhandledException += this.Application_UnhandledException;


private void Application_Startup(object sender, StartupEventArgs e)
// Load the main control
this.RootVisual = new Page();

private void Application_Exit(object sender, EventArgs e)

private void Application_UnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e)


As you can see there are three very useful methods here:

This allows you to perform any initialization that you might need to perform in your application on startup.

In order to keep the user experience sweet, I would not recommend any synchronous network calls in this method as it will delay the loading of the application.

Please notice that you must set the RootVisual property to a new instance of your Silverlight Page (plumbeed in for you automatically however).

Since this will be called when your application ends, it might be great to log this back to the server via a web service call. This really would give a great indication on the usage of your application.

I am a little concerned about this call, as it might give those nasty advertising folks a chance to spawn off more instances of the same page (might need to have check on this one, when the beta comes out).


Since the Application_UnhandledException method will get called if an unhandled exception occurs, this allows you to build a logging mechanism that could report errors directly back to your server.

I would suggest that exposing a standard web service on your server that you could call from this method. Therefore you will be able to log and review any errors in your application (i might knock up such a service soon).

No comments: