[轉載] Window Phone 7簡單的頁面間導航例子

Steps:

1.     Create a new Windows Phone Application project.

2.     In the MainPage.xaml file copy the following xaml into the ContentGrid Grid:

            <StackPanel Orientation="Vertical" VerticalAlignment="Center"  >

                <TextBox Name="ValueTextBox" Width="200" ></TextBox>

                <Button Width="200" Height="30" Content="Next Page"Click="Button_Click"></Button>

            </StackPanel>

This gives a text box for the user to enter text and a button to navigate to the next page.

3.     Copy the following event handler code to the MainPage.xaml.cs file:

        private void Button_Click(object sender, RoutedEventArgs e)

        {

            NavigationService.Navigate(new Uri(string.Format("/SecondPage.xaml?val={0}", ValueTextBox.Text),UriKind.Relative));

        }

 

The event handler uses the NavigationService.Navigate() function.  This is what makes the navigation to another page happen.  The function takes a Uri parameter with the name of the page to navigate to and the indication that it is a relative Uri to the current page.  Note also the querystring is formatted with the value entered in the ValueTextBox control – in a similar manner to a standard web querystring.

4.     Add a new Windows Phone Portrait Page to the project named SecondPage.xaml.

5.     Paste the following XAML in the ContentGrid Grid in SecondPage.xaml:

            <Button Name="GoBackButton" Width="200" Height="30" Content="Go Back" Click="Button_Click"></Button>

 

This provides a button to navigate back to the first page.

6.     Copy the following event handler code to the SecondPage.xaml.cs file:

        private void Button_Click(object sender, RoutedEventArgs e)

        {

            NavigationService.GoBack();

        }

This tells the application to go back to the previously displayed page.

7.     Add the following code to the constructor in SecondPage.xaml.cs:

            this.Loaded += new RoutedEventHandler(SecondPage_Loaded);

8.     Add the following loaded event handler to the SecondPage.xaml.cs file:

        void SecondPage_Loaded(object sender, RoutedEventArgs e)

        {

            if (NavigationContext.QueryString["val"].Length > 0)

                MessageBox.Show(NavigationContext.QueryString["val"], "Data passed"

MessageBoxButton.OK);

            else

                MessageBox.Show("{Empty}!""Data Passed",MessageBoxButton.OK);

        }

 

This code pops up a message box displaying either the text entered on the first page or the message “{Empty}!” if no text was entered.

9.     Run the application, enter some text in the text box and click on the next page button to see the application in action:

 

    

 

 

Congratulations!  You have created a new Windows Phone 7 application with page navigation.

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章