WP7 Dev – Adding Screens & Button Handlers

By | July 14, 2011

Continuing with what’s becoming the “I can’t believe it’s this easy” series of Windows Phone 7 development, this post is quick run through of how to add new screens and button handlers in a Windows Phone 7 application.

Starting with a new Windows Phone 7 application, we have to first add a new screen to navigate to. To do this, right click on the root project node and select Add –> New Item.

newScreen

 

In the window that pops up, you see we have five different elements that we can add to our project. For our sample, we’re going to add a new portrait page called SecondPage.xaml.

newScreen2

 

So as to verify that we’re actually viewing the second page, let’s change the page title to be, you guessed it, “Second Page.”

titleChange

 

Now that we have our destination set up in our project, we are going to add a button to the main page in the application that will navigate to our new page. We double click on MainPage.xaml and then drag a button control from our toolbox onto the page.

addingButton

 

We’ve called our button “Show Second Screen” to clearly indicate what we plan on doing when we click it. To navigate between screens, the Windows Phone 7 framework gives us an object called NavigationService that we can use to go back and forward between screens.

navigationService

 

To jump to our new screen, we will use the Navigate method, as shown below.

private void showSecondScreen_Click(object sender, RoutedEventArgs e)
{
    NavigationService.Navigate(new Uri("/SecondPage.xaml", UriKind.Relative));
}

 

To jump back from our new screen, we will use the GoBack method in a button handler on the second screen.

private void showFirstScreen_Click(object sender, RoutedEventArgs e)
{
    NavigationService.GoBack();
}

 

With this ridiculously simple (see the theme?) code in place, we now have a simple Windows Phone 7 application with two screens and some simple navigation between said screens. Note that you can also use the back button to unwind the navigation stack all the way back to the when the application first started. Since we’re using the GoBack method on the second screen, the only thing to unwind would be the jump from the first screen to the second screen.

Cake, eh?