Thursday, February 5, 2015

Navigation Model In Windows Phone

             User can navigate one page to another page in Windows Phone applications. Windows Phone having hardware BACK button for navigate back to previous page, But we can not navigate forward pages.

Navigation Model :
Windows Phone navigation model consists of a Fame and Pages. 

What is Frame ?

               Frame is content control that provides the ability to navigate and display content(Page). Content can be navigated by setting the Source property with the URI. Any application in Windows Phone first create phone Frame object. No need to create Frame object by default created while creating application.
             
                PhoneApplicationFrame frame=new PhoneApplicationFrame()

               Content can be navigated by using Navigate overload methods


  • Navigate(Uri)
              Navigates asynchronously to content(page) that is specified by Uri.
              Example: 
                      Navigate(new Uri("MainPage.xaml",UriKind.Relative));
  • Navigate(Uri,Object)
              Navigates asynchronously to content(page) that is specified by Uri, and passes an Object that contains data.
              Example:
                       Navigate(new Uri("MainPage.xaml"),DateTime.Now);        


What is Page ?
           
              User recognizable  collection of persistent state. Page control holds section content for the application, and page contains layout control.

Page Navigation:
  • XAML apps on windows phone uses a page based navigation model which is similar to web page navigation model.
  • Each page is identified by a URI.
  • New instance has created when page navigated to forward direction. 
Navigation Events:

When page navigates to forward or backward pages following events fired.


  • OnNavigatedTo: Event raised when the user enters into the page.
  • OnNavigatingFrom: Event raised just before the user leave the page, we can stop the navigation by using Cancel property
  • OnNavigatedFrom: Event raised after the user leaves the page.
  • OnBackKeyPress: Event raised when the user press hardware back key button on Windows Phone.


Forward Page Navigation:

Syntax:

NavigationService.Navigate(new Uri(“/pagePath/pageName”,UriKind Type));


    • Navigate method navigates one page to other.
Navigate method contains two parameters one is URI and second is UriKind


What is Uri ?

          Provides an object representation of a Uniform Resource Identifier, and Uri class defines properties and methods for handling URIs.

What is UriKind ?
  • UriKind is a enumeration.
  • UriKind defines the kind of Uris
Types of UriKind:

  • Absolute: It means absolute http Url.
  • Relative: It means relative to the root of the page in a application.
  • RelativeOrAbsolute: It covers all the basic of both.

Backward Page Navigation:


  • By default windows phone hardware button has a backward navigation functionality.
  • we can navigate the page to backward by code or we can override the functionality.


Syntax: 

NavigationService.GoBack();


Passing Data Between Pages:


  • We can pass string data only between pages using query string, similar as web.
  • Navigation request with query string values includes the query string key/value pair after a question mark (?).


Syntax: 

 

NavigationService.Navigate(new Uri(“/Path/PageName?Key=value”,UriKind type));



Get Query String Value:

  • NavigationContext represents the state of a navigation operation.
  • NavigationContext class to retrieve the query string values from navigation request.
  • Get query string values on OnNavigatedTo method.


Syntax:

string value=NavigationContext.QueryString[“Key”];

Demo:

Create Navigation Mode Application:



Create Navigation Model application in windows phone project using following steps.
  1. Launch Visual Studio Express 2010/2012.
  2. Create a new project by selecting File menu > New Project or short-cut keys Ctrl+Shift+N.
  3. Expand template Visual C# or Visual Basic  from the list of Templates on the New Project window left and select Windows Phone template.
  4. Once you select Windows Phone template, it will shows list of available built in project templates on right side of New Project window.You can choose your template depends on your requirement. I am choosing Windows Phone App template.
  5. Final step for creating project is specify Project Name and Location at the bottom of New Project window. I have created project with name "NavigationModel" and location is optional by default project directory created in installed location or you can change project directory location.
Navigation Model 

In this demo am going to explain basic navigation model in Windows Phone

  • Add page to existing application, that you can navigate from first page ( i.e.
    MainPage.xaml )
  • Right click on Solution Explorer (Ctrl + Alt + L) in your project and select Add and then AddNew (Ctrl + Shift + A).
  • Choose Windows Phone Potrait page and change name to WelcomePage.
                 


  • Change PageTitle and Application title in TitelPanel on MainPage.xaml and WelcomePage.xaml
MainPage:

<StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28">
         <TextBlock Text="Navigation Model" Style="{StaticResource PhoneTextNormalStyle}" Margin="12,0"/> 
        <TextBlock Text="Home" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}"/>
</StackPanel>                                                                                                           


WelcomePage


 <StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28"> 
       <TextBlock Text="Navigation Model" Style="{StaticResource PhoneTextNormalStyle}" Margin="12,0"/>
       <TextBlock Text="Welcome" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}"/>                                                                   
</StackPanel> 







  • Add Button control into ContentPanel on MainPage.xaml design surface from toolbox (Ctrl + Alt + x) and change text of button control to Goto welcome Page  using Content property in Property Window (Click on Button control and press F4 function key).
  • Double click on Button control it will be generate Click event handler on MainPage.xmal.cs. 

<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
          <Button Content="Goto Welcome Page" Click="gotoWelcomePage_Click"/> </Grid>


  • Add following code in gotoWelcomePage_Click event handler.

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

  • Once you click on Goto welcome Page Button its simply navigates to Welcome Page.
MainPage.xaml



  • Add following code in ContentPanel on WelcomePage.xaml design.
  • I have added three TextBlock controls on WelcomePage.xaml. I have declare first TextBlock control Name as textblock1.

 <StackPanel>

                <TextBlock Name="textblock1" Text="Hi" FontSize="80"/>

                <TextBlock Text="welcome to" FontSize="40"/>
                <TextBlock Text="learnwindowsphonebasics.blogspot.com" Foreground="YellowGreen" FontSize="40" TextWrapping="Wrap"/>
</StackPanel>

WelcomePage.xaml

  •  If you want go back (Previous page) from WelcomePage.xaml (navigate to MainPage.xaml from WelcomePage.xaml), By default windows phone having Back hardware button. If you press back hardware button on WelcomePage.xaml, its navigates to MainPage.xaml. Or we can navigate to previous  page through code.
  • Add Button on WelcomePage.xaml and change content as Goto MainPage.
  • Double click on Goto MainPage button it will generate event handler in code behind (WelcomePage.xaml.cs).   
WelcomePage.xaml
  • Add following code in GotoMainPage_Click event handler.

       private void GotoMainPage_Click(object sender, RoutedEventArgs e)

        {
            if(NavigationService.CanGoBack)
            {
                NavigationService.GoBack();
            }
        }

  • NavigationService.CanGoBack returns boolean value, if there is at least one instance of page in back navigation history its return true, otherwise its return false.
  • In the above code, before navigate to back (calling GoBack() method ) I am checking navigation history if its existing we can use GoBack() method.
  • GoBack(): method navigates most recent entry in the back navigation history.

Passing Data Between Pages:

  • Add TextBox Control from Toolbox Window (Ctrl+Alt+x) into ContentPanel MainPage.xaml design surface.

<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">

            <StackPanel>
                <TextBox Name="textbox1" />
                <Button Content="Goto Welcome Page" Click="gotoWelcomePage_Click" />
            </StackPanel>
</Grid>

  • String data only we can pass one page to another page using Query String in Uri.
  • Query String uses "?" question mark for separating url and parameters. Pass value in url after question mark using Key, Value based. like key=value.
  • Add following code in gotoWelcomePage_Click event handler.
private void gotoWelcomePage_Click(object sender, RoutedEventArgs e)
        {
            NavigationService.Navigate(new Uri("/WelcomePage.xaml?data="+textbox1.Text, UriKind.Relative));
        }
  • Above code data is key, and textbox1.Text is value.
  • After passing value to destination page (WelcomePage.xaml) now you can get the value using NavigationContext and QueryString.
  • I have implemented get the values from query string in NavigatedTo method in WelcomePage.xaml.
  • Display query string value on textblock1 control in WelcomePage.xaml

Add following code in WelcomePage.xaml.cs

protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            string value;
            if (NavigationContext.QueryString.ContainsKey("data"))
            {

                if (NavigationContext.QueryString.TryGetValue("data", out value))
                {
                    textblock1.Text ="Hi "+ value;
                }

                // OR 
                //  You can get query string value 
                // textblock1.Text = "Hi "+ NavigationContext.QueryString["data"];
            }

            base.OnNavigatedTo(e);
       }


                                          


Get the source code for Navigation Model

No comments:

Post a Comment