Thursday, April 30, 2009

Switching Pages and Passing Parameters in Silverlight

My latest project has a few pages in it and I wanted to learn the best way to switch between them. I watched Jesse Liberty's videos and they really gave me a good understanding of the mechanisms involved. I recommend you watch them both!

I found the videos really informative, and wanted to write down a simple way of switching pages and passing parameters between them in Silverlight.

1. Setting the Landing Page

You can set the first page that loads when your Silverlight app starts up, by changing the following line in App.xaml.cs:

this.RootVisual = new MyProject.Login();

My first page is a login page, where the user enters their name and password. If their login is successful, I want the page to change to the success page. I'm using Web Services to check their username and password, but we won't go into all that here :)

(Do see my previous post to learn about Web Services though!)

2. Receiving Parameters

I put a textblock on the Success.xaml page, to show the parameters when they arrive:

<TextBlock Name="welcomeText"/>

I add this method to the Success.xaml.cs page:

public void WelcomeMessage(String parm)
{
this.parm = parm;
welcomeText.Text = "Welcome " + parm;
}

The WelcomeMessage() method sets the parm parameter to the welcomeText text block, creating a nice welcome message.

3. Changing the Page & Sending Parameters

My Login.xaml page has a textbox on it that folks use to enter their user names:

<TextBox Name="userText"/>

I add the following three lines of code to the Login.xaml.cs page, wherever I want to change pages. This could be in a button click event handler, or in the case of my login app - the completed method of a web service call. So let's assume that the user has logged in successfully - and now it is time to switch to the success page:

Success page = new Success();
page.WelcomeMessage(userText.Text);
this.Content = page;

In the first line, I create a new Success page object. Then, I pass the userText String parameter to the page object's WelcomeMessage() method. In the third line, I have this.Content = page, which loads the success page. When the success page loads, it will already have had the parameters passed to it, so it will display the welcome message ;)

0 comments:

Post a Comment