Friday, May 15, 2015

Application Bar In Windows Phone

Application Bar

  • Application Bar is a pop up panel at the bottom of the application page.
  • Application Bar contains four buttons, which allows to perform some action.
  • Application Bar can not be hidden by the keyboard or other elements. when we open application bar, it will be covered entire page with transparency is set 1, then the application bar covers the screen, using transparency effect.
  • Application Bar to provide users with quick access to an application’s most common task.

Application Bar UI:


  • By default application bar is a row of icon buttons and ellipsis along the bottom of the application.
  • The application bar has built in animation that is displayed as the menu is shown or hidden.
  • Application Bar automatically adjusts when the phone changes orientation.
  • if application bar in minimize, it’s looks like



  • if we click on ellipsis on application bar





Menu Items:

  • We can add one or more text based menu items.
  • The menu items are used for application actions that are less frequently used.
  • The text of the menu items is automatically converted to all lower-case characters.
  • If we add menu items in application bar.



Application Bar Syntax:



<phone:PhoneApplicationPage.ApplicationBar>
   <shell:ApplicationBar>         
    <shell:ApplicationBarIconButton Text="Play" IconUri="[Path]" />   
</shell:ApplicationBar>
</phone:PhoneApplicationPage.ApplicationBar>


Menu Item syntax:


<phone:PhoneApplicationPage.ApplicationBar>

        <shell:ApplicationBar>           
            <shell:ApplicationBar.MenuItems>
                <shell:ApplicationBarMenuItem Text="About"/>
                <shell:ApplicationBarMenuItem Text="Help"/>                
            </shell:ApplicationBar.MenuItems>            
        </shell:ApplicationBar>
</phone:PhoneApplicationPage.ApplicationBar>


Application bar properties:



  • Mode : Specifies the size of the Application Bar when it first appears on a page, default or minimize.
  • Opacity : opacity values are between 0.0 and 1.0. The opacity of the application bar can be adjusted, but we recommend that you use only values 0.0, 0.5 and 1.0.
    • 0.0 means the Application Bar is completely transparent, the Application Bar laid over the page, so application page is not resized.
    • 0.5 means the Application Bar is partially transparent, the Application Bar laid over the page,  so application page is not resized.
    • 1.0 means the Application Bar is completely not transparent, Application Bar covers the current page, the Application page is resized to the area of the screen not occupied by Application Bar.
  • BackgroundColor : We can set the background color to Application Bar.
  • ForegroundColor : The foreground color of Application Bar, this color affected to icon buttons, labels, and the menu item text.
  • IsMenuEnabled : it’s a boolean values , it’s indicates whether user can see the menu items when they expand the Application Bar.
  • IsVisible : Indicates whether the Application Bar is visible.


Guidelines


  • Use the Application Bar instead of creating your own menu system.
  • Use default system theme colors for the application bar, if we use custom colors for application bar can affect the display quality of the button icons.
  • Avoid using long text for menu items because that text will run off screen. The recommended maximum length is between 14 to 20 characters.
  • Avoid using more than five menu items on an Application Bar, because it will force to user to scroll.

Global Application Bar

  • Global Application Bar can be reused on multiple pages in our application.
  • In App.xaml page, we need to create application bar as a static resource.


Syntax:
<Application.Resource>
//Application Bar
</Application.Resource>
Demo:
Create an application for Application Bar Demo


  • Create a new project by selecting File menu > New Project or short-cut keys Ctrl+Shift+N.
  • Choose Windows Phone Template, and change project name as "AppBarDemo"



  • MainPage.xaml:
    • We can create page level Application Bar , Add bellow code in PhoneApplicationPage

    <phone:PhoneApplicationPage.ApplicationBar>

            <shell:ApplicationBar>
                <shell:ApplicationBarIconButton Text="Previous" IconUri="/Assets/transport.rew.png" />
                <shell:ApplicationBarIconButton Text="Play" IconUri="/Assets/transport.play.png" />
                <shell:ApplicationBarIconButton Text="Next" IconUri="/Assets/transport.ff.png" />
                <shell:ApplicationBar.MenuItems>
                    <shell:ApplicationBarMenuItem Text="About"/>
                    <shell:ApplicationBarMenuItem Text="Help"/>                
                </shell:ApplicationBar.MenuItems>            
            </shell:ApplicationBar>
    </phone:PhoneApplicationPage.ApplicationBar>

    App.xaml:
    • We can create App Bar for application level (global application bar),  we need add Application as a resource in App.xaml. Add bellow code in App.xaml page

     <Application.Resources>
             <shell:ApplicationBar x:Key="globalAppBar" IsMenuEnabled="True">
                <shell:ApplicationBarIconButton Text="Previous" IconUri="/Assets/transport.rew.png" />
                <shell:ApplicationBarIconButton Text="Play" IconUri="/Assets/transport.play.png" />
                <shell:ApplicationBarIconButton Text="Next" IconUri="/Assets/transport.ff.png" />
                <shell:ApplicationBar.MenuItems>
                    <shell:ApplicationBarMenuItem Text="About"/>
                    <shell:ApplicationBarMenuItem Text="Help"/>
                </shell:ApplicationBar.MenuItems>
            </shell:ApplicationBar>        
     </Application.Resources>


    ReuseAppBar.xaml:



    • Add page to existing application, that you can reuse App Bar ( i.e.
      ReuseAppBar.xaml )
    • Add bellow code in PhoneApplicationPage

    •                     ApplicationBar="{StaticResource globalAppBar}"

      Get source code for AppBarDemo

      Friday, February 6, 2015

      Page Orientation In Windows Phone

      Orientation:

      • Windows Phone supports portrait and landscape screen orientations.
        • Types of Orientations
          • Portrait
          • Landscape Left
          • Landscape Right

      Portrait :

      • Portrait is a vertical orientation of the device.
      • By default, silverlight applications runs portrait orientation.
      • In Portrait orientation, the page oriented vertically so that the height of the page is greater than its width.

      Landscape :

      • Landscape is a horizontal orientation of the device.
      • By default, XNA application runs landscape orientation.
      • In Landscape orientation, the page oriented horizontally so that width of the page is greater than its height.

      • There is no way to specify that a page supports only landscape left or only landscape right. we have the possibility to support both or no landscape mode.

      • We can simply rotate device to initiate a change orientation to another.
      In emulator, we can switch the screen orientation by clicking the buttons in the emulator Tool bar.
      • The orientation buttons have rectangles with arrows that indicates the orientation change.
                                                   
      • We can specify the supported orientation on page level.

      • we can support different orientation on a page level, the value can be specified in code or as an attribute of the PhoneApplicationPage in XAML.

      SupportedOrientations=”Portrait”

      • Possible values of SupportedOrientations property
        • Portrait
        • Landscape
        • PortraitOrLandscape



      • We can specify orientations manually in code.

      SupportedOrientations =SupportedOrientations.Portrait; SupportedOrientations=SupportedOrientations.Landscape; SupportedOrientations=SupportedOrientations.PortraitOrLandscape;
      • Page Orientation change event:
        • In this event, we can override functionality or add more functionality the page orientation.
      eg: Change the size of the page elements.

      Syntax:

      protected override void OnOrientationChanged(OrientationChangedEventArgs e)

      {

      //write code here for override or add functionality

      base.OnOrientationChanged(e);

      }


      Scrolling Technique:

      • Avoid fixed sizes of elements, set the element's width using “*” (asterisk) or “AUTO”, these are handles elements sizes in orientation (horizontal).
      • Add Scroll viewers for containers like the stackpanel, or use elements that come with built-in scrolling capabilities, this is handles vertical size.
      • The scrolling technique uses a StackPanel or Grid layout controls with in Scrollviewer control.
      • Scrollviewer control enables the scroll, If StackPanel or Grid  control not fit in page.

      • The grid layout technique positions UI elements in a Grid. When an orientation change occurs, programmatically change the elements positions.
      • Grid layout technique, perform following steps
        • Change the SupportedOrientations property of the page to PortraitOrLandscape.
        • Use Grid for the content panel.
        • Create an OrientationChanged event handler and add code to reposition elements in the Grid.

      Demo:

      Create an application for Orientation Demo





    • Create a new project by selecting File menu > New Project or short-cut keys Ctrl+Shift+N.
    • Choose Windows Phone Template, and change project name as "Orientation Demo"

    • MainPage.xaml:



      • By default page supported orientation is Portrait.
      SupportedOrientations="Portrait"



      • I have changed SupportedOrientation Portrait to PortraitOrLandscape, Then only page supported orientations.
      SupportedOrientations="PortraitOrLandscape



      • I have created three rows for Content Panel Grid then I have added three Images each one for a row in MainPage.xaml.
      • Right click on project and create folder with name Images.
      • Add images to Images folder by right click on Images folder choose add-> add existing items.
      This demo goal is displays images vertically in Portrait orientation, and displays horizontally in Landscape orientation.

      • Add following code in MainPage.xaml


       <Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0"> <Grid.RowDefinitions> <RowDefinition Height="AUTO"/> <RowDefinition Height="AUTO"/> <RowDefinition Height="AUTO"/> </Grid.RowDefinitions> <Grid.ColumnDefinitions> <ColumnDefinition Width="AUTO"/> <ColumnDefinition Width="AUTO"/> <ColumnDefinition Width="AUTO"/> </Grid.ColumnDefinitions> <Image Name="image1" Source="/Images/1.png" Height="200"/> <Image Name="image2" Source="/Images/2.png" Height="200" Grid.Row="1"/> <Image Name="image3" Source="/Images/3.png" Height="200" Grid.Row="2"/> </Grid>

      • After added images into MainPage.xaml , its look like following image.
      • We can change controls positions programmatically in a GRID, when orientation changes occurs.
      • Create OrientationChanged event handler in a PAGE. When device or emulator changes orientation OrientationChanged event handler will be fired.
      • In Landscape, I have displaying images in a single row and three columns.


      Add following code in OrientaionChanged event handler.


      private void PhoneApplicationPage_OrientationChanged(object sender, OrientationChangedEventArgs e)

              {
                  if ((e.Orientation & PageOrientation.Portrait) == PageOrientation.Portrait)
                  {
                      Grid.SetRow(image1, 0);
                      Grid.SetRow(image2, 1);
                      Grid.SetRow(image3, 2);
                      Grid.SetColumn(image1, 0);
                      Grid.SetColumn(image3, 0);
                      Grid.SetColumn(image2, 0);
                  }
                  else
                  {
                      Grid.SetRow(image1, 0);
                      Grid.SetRow(image2, 0);
                      Grid.SetRow(image3, 0);

                      Grid.SetColumn(image1, 0);

                      Grid.SetColumn(image2, 1);
                      Grid.SetColumn(image3, 2);
                  }

              }


      Portrait
      Landscape









      Get source code for Orientation

      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