Android to Windows 8 Part 7: Adding “Back” Navigation

March 28, 2013

Over the past several weeks I’ve been working on some content I’m excited to finally share with you through a series of blog posts. This series will introduce you to Windows 8 development from an Android developer’s perspective. Through the course of the series you’ll create your first app. It won’t be anything pretty, but you’ll learn the ins and outs of the development environment, how to create a simple user interface, and how to perform navigation. Along the way you’ll see some Android Hints that will help make it easier for you to transition your existing skills to the Windows platform. You’ll also see some Visual Studio Tips to make you more productive in your development environment. Good luck!

As referred to in lesson four, there is no hardware “Back” button for Windows 8 devices. However, developers can add navigation to their apps using “Back” semantics. In this lesson you’ll learn how to navigate back to MainPage.xaml from SecondPage.xaml.

Start by opening MainPage.xaml and wrapping the <TextBlock> element in a vertical <StackPanel>. You should end up with something like this:


<StackPanel Orientation=”Vertical”>

<TextBlock x:Name=”messageFromUser” />


</StackPanel>

VISUAL STUDIO TIP

If you like your code to look “just so”, you can format it at any time by pressing Ctrl + K + D.

 

Now add a <Button> element under your <TextBlock> element, specifying the x:Name, Content, and Click attributes like so:

<StackPanel Orientation=”Vertical”>

<TextBlock x:Name=”messageFromUser” />


<Button x:Name=”goBack”


Content=”Go Back”


Click=”goBack_Click” />

</StackPanel>

Note: For the sake of this lesson a string resource was not added to Resources.resw for the message displayed in the <Button> element.

Open the code-behind file for SecondPage.xaml (press F7), and add the following method:


private
void goBack_Click(object sender, RoutedEventArgs e)

{


//Go back to MainPage.xaml if able to


if (this.Frame.CanGoBack)


this.Frame.GoBack();

}

ANDROID HINT

To perform similar navigation in Android you would enable “Up” in the action bar in your activity’s onCreate method:

 

@Override

public void onCreate(Bundle savedInstanceState) {


getActionBar().setDisplayHomeAsUpEnabled(true);


}

 

That’s all there is to it. Run your app (F5) and see what happens.

Congratulations! You just built your first Windows Store application. To learn more about building Windows Store apps, continue to follow this series. The next installment is Working with Data.

Previous Posts in this Series

  1. Setting up the Development Environment
  2. Creating Your First Windows Store Project
  3. Exploring the Windows Store Project
  4. Running the Windows Store Application
  5. Building a Simple User Interface
  6. Creating a Second Page

Additional Resources