Monday, August 17, 2009

Switching Pages with Silverlight

If you have multiple pages (User Controls) in your Silverlight app and you want a specific page to show based on the page that it is hosted in then keep reading. This technique is both powerful, fairly extensible, and easy. The main idea is that we use the Application startup event to specify the page we want to show. This is determined by a class we create called PageSwitcher. All this could be done in the App.xaml.cs, but in the interest of making this a bit more reusable, I created a PageSwitcher.cs to hold this logic.

Here are the steps to do this:

Open your App.xaml.cs and change contents of the Application_Startup event handler to the following:

this.RootVisual = PageSwitcher.Switch();

Next create a class called PageSwitcher.cs in your Silverlight project. You can copy and paste the code below.

using System;
using System.Windows;
using System.Windows.Controls;

namespace MySilverlightApp
{
public class PageSwitcher
{
/// <summary>
/// Loads the proper Page (UserControl) based on the requested url.
/// </summary>
/// <returns>An instance of the page to load.</returns>
public static UserControl Switch()
{
string url = Application.Current.Host.Source.OriginalString;

if (IsPage(url, "MyPage1"))
{
return new MyPage1();
}
else if (IsPage(url, "MyPage2"))
{
return new MyPage2();
}
else
{
throw new Exception("Unknown Page parameter for url: " + url);
}
}

/// <summary>
/// Returns true if the Page=xxx is found in the Url where xxx is the Page, else false.
/// </summary>
/// <param name="Url">The url that is used to load the .xap file</param>
/// <param name="Page">The name of the Page that is to be loaded</param>
/// <returns></returns>
private static bool IsPage(string Url, string Page)
{
return Url.ToUpper().Contains(string.Format("Page={0}", Page).ToUpper());
}
}
}

The last key to this is to make sure you pass a unique url in the .aspx page that contains your Silverlight app. Here is an example of what should use to load your silverlight application. I am not changing any (from the default code that Visual Studio 2008 generates), except adding a Page=xxx to url.

<asp:Silverlight ID="Xaml1" runat="server" Source="~/ClientBin/MySilverlightApp.xap?Page=MyPage1" MinimumVersion="2.0.31005.0" Width="100%" Height="100%" />

On the other .aspx page, I would reference the corresponding other page.

<asp:Silverlight ID="Xaml1" runat="server" Source="~/ClientBin/MySilverlightApp.xap?Page=MyPage2" MinimumVersion="2.0.31005.0" Width="100%" Height="100%" />

Now you have two .aspx pages that reference the same .xap file, but load the desired page in the Silverlight application based on a parameter passed from each of the .aspx page.

No comments: