using pivot and panorama controls

Upload: hodybenky

Post on 06-Apr-2018

224 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/3/2019 Using Pivot and Panorama Controls

    1/77

    Hands-On Lab

    Using Pivot and PanoramaControls

    Lab version: 1.0.0

    Last updated: 1/6/12

  • 8/3/2019 Using Pivot and Panorama Controls

    2/77

    Push Notifications Hands-on Lab

    CONTENTS

    Overview..........................................................................................................3

    Exercise 1: Introduction to Navigation in Windows Phone................................7

    Task 1 Creating a Windows Phone 7 Application.....................................7

    Task 2 Implementing Digg Page Functionality......................................20

    Task 3 Implementing Trends Page Functionality...................................32

    Exercise 2: Introduction to Pivot Control........................................................42

    Task 1 Adding Twitter Page...................................................................42

    Task 2 Implementing Twitter Page Functionality...................................47

    Exercise 3: Introduction to Panorama Control................................................57

    Task 1 Adding Blog Page.......................................................................57

    Task 2 Implementing Blog Page Functionality.......................................61

    Summary........................................................................................................75

    Summary

    Page | 2

  • 8/3/2019 Using Pivot and Panorama Controls

    3/77

    Push Notifications Hands-on Lab

    Overview

    Developing applications for Windows Phone 7 presents new challenges.

    How do we manage to navigate between different applications without losing

    precious battery power, but still maintain a consistent user experience with

    our application?

    How do we manage to present large quantities of information to the user

    when screen size is significantly smaller than our regular PC displays?

    All these issues are addressed and in this lab you will become familiar with

    the solutions.

    The lab walks you through creating a fully featured Microsoft Silverlight for

    Windows Phone application, named Wazup. The Wazup application will let

    you search stories using Digg, check out the tweets (Twitter messages) for

    the top 10 active trends onT witter and read posts from the Windows Phone

    Developer Blog.

    While developing the Wazup application, you will learn how to use the new

    controls for presenting information, Pivot and Panorama, and learn about the

    new navigation model in Windows Phone 7.

    Audience: The lab assumes knowledge of XAML and familiarity with Silverlight

    3.

    Objectives

    Upon completing the lab you will:

    Be familiar with most of the common controls in a Windows Phone 7application, including: TextBlock, TextBox, Button, HyperlinkButton, andListBoxBe familiar with controls specific to a Windows Phone 7 application, including:ApplicationBar, ApplicationBarIconButton, PhoneApplicationFrame, andPhoneApplicationPage

    Have a high level understand of the overall "Applications" navigation model,and specifically the page and frame navigation model within Windows Phone7 applications.Understand how to handle application state information in order to supportnavigating away from the application and backHave learned about the new controls available for Windows Phoneapplications, including Pivot and PanoramaUnderstand what a Pivot control is, how to use it, and whenUnderstand what a Panorama control is, how to use it, and when

    Page | 3

    http://www.digg.com/http://whatthetrend.com/http://twitter.com/http://windowsteamblog.com/windows_phone/b/wpdev/http://windowsteamblog.com/windows_phone/b/wpdev/http://www.digg.com/http://whatthetrend.com/http://twitter.com/http://windowsteamblog.com/windows_phone/b/wpdev/http://windowsteamblog.com/windows_phone/b/wpdev/
  • 8/3/2019 Using Pivot and Panorama Controls

    4/77

    Push Notifications Hands-on Lab

    Have created a Windows Phone 7 Silverlight application that uses both Pivotand Panorama controls to present content to the user in various ways

    Prerequisites

    The following are required to complete this hands-on lab:

    Microsoft Visual Studio 2010 Express for Windows Phone or MicrosoftVisual Studio 2010

    Windows Phone Developer Tools

    Note: All of these Tools can be downloaded together in a singlepackage from http://developer.windowsphone.com.

    Setup

    For convenience, much of the code used in this hands-on lab is available asVisual Studio code snippets. To install the code snippets:

    1. Run the .vsi installer located in the lab's Source\Setup folder.

    Note: If you have issues running the code snippets installer youcan install the code snippets manually by copying all the .snippetfiles located in the Source\Setup\CodeSnippets folder of the labto the following folder:

    My Documents\Visual Studio 2010\Code Snippets\VisualC#\My Code Snippets

    Using the Code Snippets

    With code snippets, you have all the code you need at your fingertips. The labdocument will tell you exactly when you can use them. For example,

    Figure 1Using Visual Studio code snippets to insert code into your project

    Page | 4

    http://developer.windowsphone.com/http://developer.windowsphone.com/
  • 8/3/2019 Using Pivot and Panorama Controls

    5/77

    Push Notifications Hands-on Lab

    To add this code snippet in Visual Studio, you simply place the cursor whereyou would like the code to be inserted, start typing the snippet name (withoutspaces or hyphens), watch as IntelliSense picks up the snippet name, andthen press the Tab key twice when the snippet you want is selected. The

    code will be inserted at the cursor location.

    Figure 2Start typing the snippet name

    Figure 3Press Tab to select the highlighted snippet

    Figure 4Press Tab again to expand the snippet

    To insert a code snippet using the mouse rather than the keyboard, right-click where you want to insert the code snippet, select Insert Snippetfollowed by My Code Snippets and then pick the relevant snippet from thelist.

    To learn more about Visual Studio IntelliSense Code Snippets, including howto create your own, see http://msdn.microsoft.com/en-us/library/ms165392.aspx .

    Page | 5

    http://msdn.microsoft.com/en-us/library/ms165392.aspxhttp://msdn.microsoft.com/en-us/library/ms165392.aspxhttp://msdn.microsoft.com/en-us/library/ms165392.aspxhttp://msdn.microsoft.com/en-us/library/ms165392.aspx
  • 8/3/2019 Using Pivot and Panorama Controls

    6/77

    Push Notifications Hands-on Lab

    Exercises

    This hands-on lab comprises the following exercises:

    1. Introduction to Navigation in Windows Phone

    2. Introduction to Pivot Control

    3. Introduction to Panorama Control

    Estimated time to complete this lab: 90 minutes.

    Page | 6

  • 8/3/2019 Using Pivot and Panorama Controls

    7/77

    Push Notifications Hands-on Lab

    Exercise 1: Introduction to

    Navigation in Windows PhoneIn this exercise we will build an application named Wazup. At the end of thisexercise the Wazup application will allow us to search stories on Digg andsee the active Trends on Twitter.

    The exercise will include the following tasks:

    Create basic Windows Phone 7 Application placeholder pagesImplement Digg search page functionalityImplement Trends page functionalityWe will use the Microsoft Visual Studio 2010 Express for Windows Phonedevelopment environment, and will deploy to the Windows Phone Emulatorfor debugging. The solution we will be working with is based upon theSilverlight for Windows Phone Application template. During development, wewill add Silverlight for Windows Phone project specific items: Windows PhonePortrait Page, Windows Phone Pivot Page and Windows Phone PanoramaPage.

    Note: The steps in this hands-on lab illustrate procedures using MicrosoftVisual Studio 2010 Express for Windows Phone, but they are equallyapplicable to Microsoft Visual Studio 2010 with the Windows PhoneDeveloper Tools. Instructions that refer generically to Visual Studio applyto both products.

    Task 1 Creating a Windows Phone 7 Application

    In this task we will create the basic Windows Phone 7 project for the Wazupapplication.

    At the end of this task the Wazup application will have two pages in additionto the main page.

    The first page is a placeholder for the Digg functionality and the second pageis a placeholder for the trends functionality. We will add functionality to thesetwo pages in the following two tasks.

    During this task we will see how to work with the Windows Phone Application

    Bar and how to navigate between pages in a Windows Phone application.

    Since this is rather a big application, well start with adding some code, artand XAML that weve prepare in advance to allow you to fully focus on thecore Windows Phone fundamentals.

    1. Open Microsoft Visual Studio 2010 Express for Windows Phone fromStart | All Programs | Microsoft Visual Studio 2010 Express |Microsoft Visual Studio 2010 Express for Windows Phone.

    Page | 7

  • 8/3/2019 Using Pivot and Panorama Controls

    8/77

    Push Notifications Hands-on Lab

    Visual Studio 2010: Open Visual Studio 2010 from Start | AllPrograms | Microsoft Visual Studio 2010.

    1. Add a new project of type Windows Phone Application, named

    Wazup.

    Figure 5Adding new Windows Phone Application project

    Page | 8

  • 8/3/2019 Using Pivot and Panorama Controls

    9/77

    Push Notifications Hands-on Lab

    1. Add the files WazupAppIcon.png and WazupStartIcon.png fromthe Assets folder of this lab located in Source\Assets. These iconswill be our application icon in the application list (or Windows PhoneStart screen). To do this, right-click on Wazup (project name) andselect AddExisting Item:

    Figure 6Add Existing Item to project

    1. Select the two files added, and change the:

    Build Action property to Content Copy to Output Directory property to Copy if newer

    Page | 9

  • 8/3/2019 Using Pivot and Panorama Controls

    10/77

    Push Notifications Hands-on Lab

    1. Open the file WMAppManifest.xml, located in the projectProperties folder.

    Figure 7Location of WMAppManifest.xml

    1. Find the element Deployment | App | IconPath and change its valuefrom ApplicationIcon.png to WazupAppIcon.png. This icon is thetile icon representing the application in the application list.

    2. Find the element Deployment | App | Tokens | PrimaryToken |TemplateType5 | BackgroundImageURI and change its value fromBackground.png to WazupStartIcon.png. This image is used whenthe application is pinned to the Start screen.

    3. Add the file Styles.xaml from the Assets folder of this lab located inSource\Assets. To do this, right-click on Wazup (project name) andSelect Add Existing Item

    4. Open the file App.xaml and add the following code into the resourcessection:

    (Code Snippet Using Pivot and Panorama Ex 1 Task 1 Step 9 Styles.xaml)

    XAML

    Page | 10

  • 8/3/2019 Using Pivot and Panorama Controls

    11/77

    Push Notifications Hands-on Lab

    1. Add a folder to the project, named Resources. To do this right-click onWazup (project name) and select AddNew Folder.

    Figure 8Add new folder to the project

    1. Add all the files that are located in this labsSource\Assets\Resources folder to the new Wazup projectResources folder. Youve just added few images that well use andreference from our XAML and code during the lab.

    Select all the files in the Resources folder and change the Build Actionproperty to Content.

    Page | 11

  • 8/3/2019 Using Pivot and Panorama Controls

    12/77

    Push Notifications Hands-on Lab

    1. This will cause the images to be added to the XAP file instead of asresources inside the DLL file.

    Figure 9Change Build Action for added resources

    Page | 12

  • 8/3/2019 Using Pivot and Panorama Controls

    13/77

    Push Notifications Hands-on Lab

    1. Add another folder to the project, named Views.

    2. Add a new item to the Views folder by right-clicking the Views folderand selecting Add->New Item

    Figure 10Add new item to the project

    1. Select Windows Phone Portrait Page and name it DiggPage.xaml

    Page | 13

  • 8/3/2019 Using Pivot and Panorama Controls

    14/77

    Push Notifications Hands-on Lab

    Figure 11Add new Windows Phone Portrait Page

    1. Add another Windows Phone Portrait Page namedTrendsPage.xaml

    2. Open MainPage.xaml

    Most of the prep work is behind us. Now it is time to define ourapplications UI. Well start by defining the main page UI.

    3. Locate the LayoutRoot grid and replace the content with thefollowing code. This code adds 3 buttons to the main page. Eachbutton will link to a different page in the application.

    (Code Snippet Using Pivot and Panorama Ex 1 Task 1 Step 18 MainPageLayoutRoot)

    XAML

    There is a small section at the bottom of the Windows PhoneApplication Bar screen that we can use for adding up to 4 button

    Page | 14

  • 8/3/2019 Using Pivot and Panorama Controls

    15/77

    Push Notifications Hands-on Lab

    icons. We can also add menu items to the application bar that willdisplay when the user presses the "three dots" () icon.

    1. To add buttons to the phone application bar, instead of thecommented use ofPhoneApplicationPage.ApplicationBar, add thefollowing after the LayoutRoot grid element:

    (Code Snippet Using Pivot and Panorama Ex 1 Task 1 Step 19 MainPageApplicatioBar)

    XAML

    1. Add a new class named Navigation by right-clicking Wazup (projectname) and selecting AddClassThis class will provide a helperfunction to help us navigate between the application pages.

    Now we will implement the Navigation class. First we define an enum

    that contains an entry for each page in our final application: The Navigation class provides an extension method of

    PhoneApplicationPage, named GoToPage, which allows usto navigate to a requested page

    The GoToPage function uses a property ofPhoneApplicationPage, named NavigationService totrigger the navigation

    1. Replace the content of the Navigation.cs file with the following code

    (Code Snippet Using Pivot And Panorama Ex 1 Task 1 Step 21 Navigation.cs)

    C#

    using System;using Microsoft.Phone.Controls;

    namespace Wazup{ publicenum ApplicationPages

    {

    Page | 15

  • 8/3/2019 Using Pivot and Panorama Controls

    16/77

    Push Notifications Hands-on Lab

    Digg,Trends,Twitter,Blog

    }

    public static class Navigation{

    /// /// Goes to page.

    //////The application

    page. publicstaticvoid GoToPage(thisPhoneApplicationPagephoneApplicationPage, ApplicationPages applicationPage)

    { switch (applicationPage)

    { caseApplicationPages.Digg:

    phoneApplicationPage.NavigationService.Navigate(newUri("/Views/DiggPage.xaml", UriKind.Relative)); break;

    caseApplicationPages.Trends:phoneApplicationPage.NavigationService.Naviga

    te(newUri("/Views/TrendsPage.xaml", UriKind.Relative)); break;

    caseApplicationPages.Twitter:

    phoneApplicationPage.NavigationService.Navigate(newUri("/Views/TwitterPage.xaml", UriKind.Relative)); break;

    caseApplicationPages.Blog:phoneApplicationPage.NavigationService.Naviga

    te(newUri("/Views/BlogPage.xaml", UriKind.Relative)); break;

    }}

    }}

    1. Open the file MainPage.xaml.cs

    2. Add the following event handlers below the constructor of theMainPage class. In this step we handle the button Clickevents forboth the buttons we have added and the application bar buttons. Ineach event handler we use the Navigation class to go the correct

    Page | 16

  • 8/3/2019 Using Pivot and Panorama Controls

    17/77

    Push Notifications Hands-on Lab

    page. Note that the blog page doesn't exist yet; it will be created laterin this lab.

    (Code Snippet Using Pivot and Panorama Ex 1 Task 1 Step 23 MainPageEvent Handler)

    C#

    ////// Handles the Click event of the ButtonDigg control.//////The source of the event.///The instance containing theevent data.privatevoid ButtonDigg_Click(object sender, RoutedEventArgs e){ this.GoToPage(ApplicationPages.Digg);}

    ////// Handles the Click event of the ButtonTwitter control.//////The source of the event.///The instance containing theevent data.privatevoid ButtonTwitter_Click(object sender, RoutedEventArgse){ this.GoToPage(ApplicationPages.Trends);

    }

    ////// Handles the Click event of the ButtonBlog control.//////The source of the event.///The instance containing theevent data.privatevoid ButtonBlog_Click(object sender, RoutedEventArgs e){ this.GoToPage(ApplicationPages.Blog);

    }

    #region Appbar handlers

    ////// Handles the Click event of the AppbarButtonDigg control.//////The source of the event.

    Page | 17

  • 8/3/2019 Using Pivot and Panorama Controls

    18/77

    Push Notifications Hands-on Lab

    ///The instancecontaining the event data.privatevoid AppbarButtonDigg_Click(object sender, EventArgs e){ this.GoToPage(ApplicationPages.Digg);

    }

    ////// Handles the Click event of the AppbarButtonTwitter control.//////The source of the event.///The instancecontaining the event data.privatevoid AppbarButtonTwitter_Click(object sender, EventArgse){ this.GoToPage(ApplicationPages.Trends);

    }

    ////// Handles the Click event of the AppbarButtonBlog control.//////The source of the event.///The instancecontaining the event data.privatevoid AppbarButtonBlog_Click(object sender, EventArgs e){ this.GoToPage(ApplicationPages.Blog);}

    #endregion

    1. Compile and run the application

    Page | 18

  • 8/3/2019 Using Pivot and Panorama Controls

    19/77

    Push Notifications Hands-on Lab

    2. At this stage the application looks like the following:

    Figure 12Opening screen of Wazup application

    1. Stop the debugging and return to the code. This step concludes thecurrent task.

    Task 2 Implementing Digg Page Functionality

    In this task we will implement the functionality of the Digg search page inthe Wazup application. At the end of this task the Wazup applicationwill have a working Digg search page.

    During this task we will create the Digg page UI using some basic controlslike TextBox, TextBlock, HyperlinkButton and ListBox. In addition, wewill see how to save and load page state when navigating away fromthe application.

    Page | 19

  • 8/3/2019 Using Pivot and Panorama Controls

    20/77

    Push Notifications Hands-on Lab

    1. Add references to the System.Xml.Linq andSystem.Runtime.Serialization assemblies (from .NET tab). Theseassemblies are needed for the Digg service utility class that we willadd shortly.

    Figure 13Add references to System.Xml.Linq and System.Runtime.Serialization

    1. Now we will add the utility classes used to work with Digg service. Inorder to do that, add a folder named Services to the project.

    Page | 20

  • 8/3/2019 Using Pivot and Panorama Controls

    21/77

    Push Notifications Hands-on Lab

    2. Add to the Services folder the files: DiggService.cs andDiggStory.cs which are located in Source\Assets\Services folder ofthis lab. These classes handle the web requests for you, getting therelevant date from Digg.

    Figure 14

    Solution Explorer after adding the Digg service files into the Servicesfolder

    1. Add a folder named Helpers to the project. In this folder we will storeseveral helper controls that we will use.

    2. Inside the folder Helpers, add a folder named ProgressBar

    3. Add to the ProgressBar folder all the files from theSource\Assets\Helpers\ProgressBar folder of this lab. The followingfiles should be added: BooleanToVisibilityConverter.cs,ProgressBarWithText.xaml, ProgressBarWithText.xaml.csand

    RelativeAnimatingContentControl.cs.These files encapsulate aprogress bar that have similar UI of the one used by Windows Phone.

    Figure 15Solution Explorer after adding ProgressBar files

    1. Open the file DiggPage.xaml

    Page | 21

  • 8/3/2019 Using Pivot and Panorama Controls

    22/77

    Push Notifications Hands-on Lab

    2. Add the following XML namespace to thephone:PhoneApplicationPage element next to the other XMLnamespaces definitions:

    XAML

    xmlns:localHelpers="clr-namespace:Wazup.Helpers"

    1. Set the DataContext property of the DiggPage to be the DiggPageitself by adding the following line to thephone:PhoneApplicationPage element:

    XAML

    DataContext="{Binding RelativeSource={RelativeSource Self}}"

    Now we will define the UI for the Digg page.

    1. Locate the LayoutRoot grid and replace the content with thefollowing code. The Digg page has a TextBox that contains the text tobe searched, a search Button, a TextBlockthat presents the lastsearched text, a ListBox that will present the search results and aProgressBarWithText control that will show status information whilesearching.

    Note that the ProgressBarWithText control is a custom controlthat we have added to the project.

    The ListBox control is used to present a list of items. The ListBox items areset via the property ItemsSource which is bound to a collection of

    DiggStory items. In order to transform each DiggStory object into a valid UIwe use the ItemTemplate property to define the name of theDataTemplate that will do the transformation. The DataTemplate will bedefined in the next step.

    (Code Snippet Using Pivot and Panorama Ex 1 Task 2 Step 11 DiggPageLayoutRoot)

    XAML

    Page | 22

  • 8/3/2019 Using Pivot and Panorama Controls

    23/77

    Push Notifications Hands-on Lab

    Now we define a DataTemplate that will transform each DiggStoryobject into a presentable UI that contains the Digg story.

    1. Add the following code into DiggPage resources section after the endof the PhoneApplicationPage element.

    (Code Snippet Using Pivot and Panorama Ex 1 Task 2 Step 12 DiggPageResources)

    XAML

    Page | 23

  • 8/3/2019 Using Pivot and Panorama Controls

    24/77

    Push Notifications Hands-on Lab

    1. We now add buttons to the application bar in the Digg page. After theLayoutRoot grid ends, instead of the commented use ofPhoneApplicationPage.ApplicationBar, add the following code:

    (Code Snippet Using Pivot and Panorama Ex 1 Task 2 Step 13 DiggPageApplicationBar)

    XAML

    1. Add a new class named StateManager by right-clicking Wazup(project name) and selecting AddClassThis class will providehelper functions for saving and loading state information when theapplication exits.

    In order to save battery power Windows Phone 7 doesn't allowapplications to run simultaneously. This means that if you open anew application while your application is running (for example, WebBrowser), it will cause your application to exit. If you then return to

    Page | 24

  • 8/3/2019 Using Pivot and Panorama Controls

    25/77

    Push Notifications Hands-on Lab

    your application by clicking Back, your application will open in a newinstance (that is, an entirely different process). The application willbe opened in the last opened page, since this information is saved bythe operating system, but if the page had any information stored inits variables, that information will be completely erased, since this isa new instance of the page. In order to overcome this situation youneed to:

    Save variables information into a special state object when thepage is being navigated away from (that is, the user is leavingthe page)

    Load the variables information from the special state objectwhen the page is being navigated back to (that is, the user isreturning to the page)

    Do this in the two functions OnNavigateTo and OnNavigateFrom.

    1. To prepare a helper class named StateManager that will help usimplement these two functions, replace the content of theStateManager.cs file with the following code snippet:

    (Code Snippet Using Pivot and Panorama Ex 1 Task 2 Step 15 StateManager.cs)

    C#

    using System;using Microsoft.Phone.Controls;

    namespace Wazup{

    ///

    /// State Manager///public static class StateManager{

    /// /// Saves a key-value pair into the state object

    //////The phone

    application page.///The key.///The value.

    publicstaticvoid SaveState(thisPhoneApplicationPage

    phoneApplicationPage, string key, object value){

    if (phoneApplicationPage.State.ContainsKey(key)){

    phoneApplicationPage.State.Remove(key);}

    phoneApplicationPage.State.Add(key, value);

    Page | 25

  • 8/3/2019 Using Pivot and Panorama Controls

    26/77

    Push Notifications Hands-on Lab

    }

    /// /// Loads value from the state object, according to thekey.

    /////////The phone

    application page.///The key.///The loaded value

    publicstatic T LoadState(thisPhoneApplicationPagephoneApplicationPage, string key) where T : class

    { if (phoneApplicationPage.State.ContainsKey(key))

    {

    return (T)phoneApplicationPage.State[key];}

    returndefault(T);}

    }}

    1. Open the file DiggPage.xaml.cs

    2. Replace the using section ofDiggPage class with the following codesnippet:

    (Code Snippet Using Pivot and Panorama Ex 1 Task 2 Step 17 DiggPageUsing)

    C#

    using System;using System.Collections.Generic;using System.Collections.ObjectModel;using System.Windows;using Microsoft.Phone.Controls;using Wazup.Services;

    1. Add to the DiggPage class the following dependency properties: SearchText of type string used to save the current search

    text LastSearchText of type string used to save the last search

    text DiggSearchResults of type

    ObservableCollection - used to save thecollection of digg search results

    Page | 26

  • 8/3/2019 Using Pivot and Panorama Controls

    27/77

    Push Notifications Hands-on Lab

    IsSearching of type bool used to indicate whether search iscurrently in progress

    Use the following code snippet:

    (Code Snippet Using Pivot and Panorama Ex 1 Task 2 Step 17 DiggPageProperties)

    C#

    #region SearchText

    ////// SearchText Dependency Property///publicstaticreadonlyDependencyPropertySearchTextProperty =

    DependencyProperty.Register("SearchText",typeof(string), typeof(DiggPage), newPropertyMetadata((string)""));

    ////// Gets or sets the SearchText property. This dependencyproperty/// indicates the text to be searched.///publicstring SearchText{ get { return (string)GetValue(SearchTextProperty); } set { SetValue(SearchTextProperty, value); }}

    #endregion

    #region LastSearchText

    ////// LastSearchText Dependency Property///publicstaticreadonlyDependencyPropertyLastSearchTextProperty =

    DependencyProperty.Register("LastSearchText",typeof(string), typeof(DiggPage), newPropertyMetadata((string)""));

    ////// Gets or sets the LastSearchText property. Thisdependency property/// indicates the last searched text.///publicstring LastSearchText{

    Page | 27

  • 8/3/2019 Using Pivot and Panorama Controls

    28/77

    Push Notifications Hands-on Lab

    get { return(string)GetValue(LastSearchTextProperty); } set { SetValue(LastSearchTextProperty, value); }}

    #endregion

    #region DiggSearchResults

    ////// DiggSearchResults Dependency Property///publicstaticreadonlyDependencyPropertyDiggSearchResultsProperty =

    DependencyProperty.Register("DiggSearchResults",typeof(ObservableCollection), typeof(DiggPage), new

    PropertyMetadata((ObservableCollection) null));

    ////// Gets or sets the DiggSearchResults property. Thisdependency property/// indicates digg search results.///public ObservableCollection DiggSearchResults{ get { return(ObservableCollection)GetValue(DiggSearchResultsProperty); }

    set { SetValue(DiggSearchResultsProperty, value); }}

    #endregion

    #region IsSearching

    ////// IsSearching Dependency Property///publicstaticreadonlyDependencyPropertyIsSearchingProperty =

    DependencyProperty.Register("IsSearching",typeof(bool), typeof(DiggPage), newPropertyMetadata((bool)false));

    ////// Gets or sets the IsSearching property. This dependencyproperty/// indicates whether we are currently searching.

    Page | 28

  • 8/3/2019 Using Pivot and Panorama Controls

    29/77

    Push Notifications Hands-on Lab

    ///publicbool IsSearching{ get { return (bool)GetValue(IsSearchingProperty); } set { SetValue(IsSearchingProperty, value); }

    }

    #endregion

    1. Add a handler for the Clickevent of the ButtonSearch control. In thishandler we perform initiate a search in Digg service. We do this bycalling the asynchronous method DiggService.Search which acceptsthe search text, a callback function to call when the search is completeand a callback function to call if the search failed, for example, if theDigg service is not available. If the search completes successfully, weadd the results to the DiggSearchResults collection which is boundto the ListBox.

    (Code Snippet Using Pivot and Panorama Ex 1 Task 2 Step 19 DiggPageButtonSearch Click)

    C#

    ////// Handles the Click event of the ButtonSearch control.//////The source of the event.///The instance containing theevent data.

    privatevoid ButtonSearch_Click(object sender, RoutedEventArgs e){ if (string.IsNullOrEmpty(SearchText))

    { return;

    }

    IsSearching = true; DiggService.Search(SearchText, delegate(IEnumerable diggSearchResults)

    {IsSearching = false;

    LastSearchText = SearchText;

    DiggSearchResults = newObservableCollection();

    foreach (DiggStory diggSearchResult indiggSearchResults)

    Page | 29

  • 8/3/2019 Using Pivot and Panorama Controls

    30/77

    Push Notifications Hands-on Lab

    {DiggSearchResults.Add(diggSearchResult);

    }},

    delegate(string searchText, Exception exception)

    { IsSearching = false;LastSearchText = string.Format("Error while searching

    {0}.", searchText);System.Diagnostics.Debug.WriteLine(exception);

    });}

    1. Override the functions OnNavigateTo and OnNavigateFrom of thepage. Use the StateManager class to save and load page state whenthe current page is changing.

    (Code Snippet Using Pivot and Panorama Ex 1 Task 2 Step 20 DiggPageNavigation)

    C#

    privateconststring SearchTextKey = "SearchTextKey";privateconststring LastSearchTextKey = "LastSearchTextKey";privateconststring DiggSearchResultsKey ="DiggSearchResultsKey";

    protectedoverridevoidOnNavigatedFrom(System.Windows.Navigation. NavigationEventArgs e){

    this.SaveState(SearchTextKey, SearchText); this.SaveState(LastSearchTextKey, LastSearchText); this.SaveState(DiggSearchResultsKey, DiggSearchResults);}

    protectedoverridevoidOnNavigatedTo(System.Windows.Navigation. NavigationEventArgs e){

    SearchText = this.LoadState(SearchTextKey);LastSearchText = this.LoadState(LastSearchTextKey);DiggSearchResults =

    this.LoadState(DiggSearchResults

    Key);}

    1. Add the following event handlers in the DiggPage class. In this stepwe handle the application bar buttons. In each event handler we usethe Navigation class to go to the correct page. Note that the blogpage doesn't exist yet; we we will create it later in this lab.

    Page | 30

  • 8/3/2019 Using Pivot and Panorama Controls

    31/77

    Push Notifications Hands-on Lab

    (Code Snippet Using Pivot and Panorama Ex 1 Task 2 Step 21 DiggPageEvent Handler)

    C#

    #region Appbar handlers

    ////// Handles the Click event of the AppbarButtonDigg control.//////The source of the event.///The instancecontaining the event data.privatevoid AppbarButtonDigg_Click(object sender, EventArgs e){

    SearchText = string.Empty;LastSearchText = string.Empty;DiggSearchResults = null;

    }

    ////// Handles the Click event of the AppbarButtonTwitter control.//////The source of the event.///The instancecontaining the event data.privatevoid AppbarButtonTwitter_Click(object sender, EventArgse){ this.GoToPage(ApplicationPages.Trends);

    }

    ////// Handles the Click event of the AppbarButtonBlog control.//////The source of the event.///The instancecontaining the event data.privatevoid AppbarButtonBlog_Click(object sender, EventArgs e){ this.GoToPage(ApplicationPages.Blog);}

    #endregion

    1. Compile and run the application. If you get an error while searchingDigg it might be because the Digg search service is down. You cancheck the status of the service at:http://developers.digg.com/known_issues

    Page | 31

    http://developers.digg.com/known_issueshttp://developers.digg.com/known_issues
  • 8/3/2019 Using Pivot and Panorama Controls

    32/77

    Push Notifications Hands-on Lab

    2. At this stage the Digg search page should work and look like thefollowing:

    Figure 16Digg search page with results

    Stop the debugging and return to the code.

    1. This step concludes the current task.

    Task 3 Implementing Trends Page Functionality

    In this task we will implement the functionality of the Trends page in theWazup application. At the end of this task the Wazup application will have aworking Trends page.

    Page | 32

  • 8/3/2019 Using Pivot and Panorama Controls

    33/77

    Push Notifications Hands-on Lab

    During this task we will create the Trends page UI using some basic controlsand handle the state of the Trends page when navigating away from theapplication.

    1. Add reference to the System.Servicemodel.Web assembly (from the.NET tab). This assembly is needed for the Twitter service utility class

    that we will add shortly.

    Figure 17Add reference to System.Servicemodel.Web

    Now we will add the utility classes used to work with Trends service.Add to the Services folder the files: TwitterService.cs, Trend.csand Twit.cs which are located in Source\Assets\Services folder of

    Page | 33

  • 8/3/2019 Using Pivot and Panorama Controls

    34/77

    Push Notifications Hands-on Lab

    this lab.

    Figure 18

    Solution Explorer after adding trends service files into the Servicesfolder

    1. Since the trends service provider limits its access using an applicationkey, you must create one for your lab. To do this, go to the sitehttp://api.whatthetrend.com/; select "Request API key," which you canfind on the right side of the display. Fill out the small form to get a freeapplication key that you can use for the lab. Copy the generated keyto the constant Wazup_WhatTheTrendApplicationKey that isdefined in the file TwitterService.cs.

    Do not use the default key since it probably will not work.

    Figure 19Requesting an application key from WhatTheTrend.com

    Page | 34

    http://api.whatthetrend.com/http://api.whatthetrend.com/
  • 8/3/2019 Using Pivot and Panorama Controls

    35/77

    Push Notifications Hands-on Lab

    1. Open the file TrendsPage.xaml

    2. Add the following XML namespace to thephone:PhoneApplicationPage element next to the other XMLnamespaces definitions:

    XAML

    xmlns:localHelpers="clr-namespace:Wazup.Helpers"

    1. Set the DataContext property of the TrendsPage to be theTrendsPage itself. Do this by adding the following line to thephone:PhoneApplicationPage element:

    XAML

    DataContext="{Binding RelativeSource={RelativeSource Self}}"

    1. Now we will define the UI for the trends page. Locate the LayoutRootgrid and replace the content with the following code.The trends pagehas a ListBox that will present the list of top 10 Twitter trends, aProgressBarWithText control that will show status information whileloading trends and a TextBlockthat presents an attribution for thetrends service supplier (whatthetrend.com). The ListBox items are setvia the property ItemsSource which is bound to a collection ofTrenditems. In order to transform each Trend object into a valid UI we usethe ItemTemplate property to define the name of the DataTemplatethat will do the transformation. We will define the DataTemplate inthe next step.

    (Code Snippet Using Pivot and Panorama Ex 1 Task 3 Step 7 TrendsPageLayoutRoot)

    XAML

    Page | 35

  • 8/3/2019 Using Pivot and Panorama Controls

    36/77

    Push Notifications Hands-on Lab

    1. Now we define a DataTemplate that will transform each Trendobject into a presentable UI that contains the trend. Add the followingcode into TrendsPage resources section.

    (Code Snippet Using Pivot and Panorama Ex 1 Task 3 Step 8 TrendsPageResources)

    XAML

    1. We now add buttons to the application bar in the trends page. Afterthe LayoutRoot grid ends, instead of the commented use ofPhoneApplicationPage.ApplicationBar, add the following code:

    (Code Snippet Using Pivot and Panorama Ex 1 Task 3 Step 8 TrendsPageApplicationBar)

    XAML

    Page | 36

  • 8/3/2019 Using Pivot and Panorama Controls

    37/77

    Push Notifications Hands-on Lab

    1. Open the file TrendsPage.xaml.cs

    2. Replace the using section of the TrendsPage class with the followingcode snippet:

    (Code Snippet Using Pivot and Panorama Ex 1 Task 3 Step 11

    TrendsPage Using)

    C#

    using System;using System.Collections.Generic;using System.Collections.ObjectModel;using System.Windows;using System.Windows.Controls;using System.Windows.Input;using Microsoft.Phone.Controls;using Wazup.Services;

    1. Add to the TrendsPage class the following dependency properties:

    Trends of type ObservableCollection - used to savethe collection of Twitter trends

    IsTrendsLoading of type bool used to indicate whethertrends loading is currently in progress

    Use the following code snippet:

    (Code Snippet Using Pivot and Panorama Ex 1 Task 3 Step 7 TrendsPageProperties)

    C#

    #region Trends

    ////// Trends Dependency Property///publicstaticreadonlyDependencyProperty TrendsProperty = DependencyProperty.Register("Trends",typeof(ObservableCollection), typeof(TrendsPage), newPropertyMetadata((ObservableCollection)null));

    Page | 37

  • 8/3/2019 Using Pivot and Panorama Controls

    38/77

    Push Notifications Hands-on Lab

    ////// Gets or sets the Trends property. This dependency property/// indicates the current twitter trends.///

    public ObservableCollection Trends{ get { return(ObservableCollection)GetValue(TrendsProperty); } set { SetValue(TrendsProperty, value); }}

    #endregion

    #region IsTrendsLoading

    ///

    /// IsTrendsLoading Dependency Property///publicstaticreadonlyDependencyProperty IsTrendsLoadingProperty=

    DependencyProperty.Register("IsTrendsLoading", typeof(bool),typeof(TrendsPage), newPropertyMetadata((bool)false));

    ////// Gets or sets the IsTrendsLoading property. This dependencyproperty/// indicates whether we are currently loading trends.

    ///publicbool IsTrendsLoading{ get { return (bool)GetValue(IsTrendsLoadingProperty); } set { SetValue(IsTrendsLoadingProperty, value); }}

    #endregion

    1. Add a handler for the MouseLeftButtonUp event of theTextBlockTrend control. Currently we will leave it empty. We will add

    functionality as the lab progress.(Code Snippet Using Pivot and Panorama Ex 1 Task 3 Step 13 TrendsPage TextBlockTrend MouseLeftButtonUp Empty)

    C#

    ////// Handles the MouseLeftButtonUp event of the TextBlockTrendcontrol.

    Page | 38

  • 8/3/2019 Using Pivot and Panorama Controls

    39/77

    Push Notifications Hands-on Lab

    //////The source of the event.///The instancecontaining the event data.

    privatevoid TextBlockTrend_MouseLeftButtonUp(object sender,MouseButtonEventArgs e){

    }

    1. Override the functions OnNavigateTo and OnNavigateFrom of thepage. Use the StateManager class to save and load page state whenthe current page is changing. In the function OnNavigateTo we needto check whether we loaded Trends from the state object whichimplies the user have already seen this page and navigated from him.If we didn't, then it is a sign that we loaded from a new instance thispage, and so need to get the Trends information from the trendsservice. We do this by calling the asynchronous methodTwitterService.GetTrends, which accepts a callback function to callwhen the trends loading is complete and a callback function to call ifthe trends loading failed, for example, the trends service is notavailable. If the trends loading completed successfully we add theresults to the Trends collection which is bound to the ListBox.

    (Code Snippet Using Pivot and Panorama Ex 1 Task 3 Step 14 TrendsPage State Handling)

    C#

    private const string TrendsKey = "TrendsKey";

    protected override voidOnNavigatedFrom(System.Windows.Navigation. NavigationEventArgs e){

    this.SaveState(TrendsKey, Trends);}

    protected override voidOnNavigatedTo(System.Windows.Navigation. NavigationEventArgs e){

    Trends =

    this.LoadState(TrendsKey);

    if (Trends == null){

    IsTrendsLoading = true; TwitterService.GetTrends(

    delegate(IEnumerable trends){

    IsTrendsLoading = false;

    Page | 39

  • 8/3/2019 Using Pivot and Panorama Controls

    40/77

    Push Notifications Hands-on Lab

    Trends = new ObservableCollection();

    foreach (Trend trend in trends){

    Trends.Add(trend);}},delegate(Exception exception){

    IsTrendsLoading = false;System.Diagnostics.Debug.WriteLine(exception);

    });}

    }

    Add the following event handlers in the TrendsPage class.

    1. In this step we handle the application bar buttons. In each eventhandler we use the Navigation class to go the correct page. Note thatthe blog page doesn't exist yet; it will be created later in this lab.

    (Code Snippet Using Pivot and Panorama Ex 1 Task 3 Step 15 TrendsPage Event Handler)

    C#

    #region Appbar handlers

    ////// Handles the Click event of the AppbarButtonDigg control.

    //////The source of the event.///The instancecontaining the event data.privatevoid AppbarButtonDigg_Click(object sender, EventArgs e){ this.GoToPage(ApplicationPages.Digg);}////// Handles the Click event of the AppbarButtonTwitter control.//////The source of the event.///The instancecontaining the event data.privatevoid AppbarButtonTwitter_Click(object sender, EventArgse){}////// Handles the Click event of the AppbarButtonBlog control.

    Page | 40

  • 8/3/2019 Using Pivot and Panorama Controls

    41/77

    Push Notifications Hands-on Lab

    //////The source of the event.///The instancecontaining the event data.privatevoid AppbarButtonBlog_Click(object sender, EventArgs e)

    { this.GoToPage(ApplicationPages.Blog);}

    #endregion

    1. Compile and run the application.

    At this stage the trends page should work and look like the following:

    Figure 20Trends page showing Twitter trends

    Page | 41

  • 8/3/2019 Using Pivot and Panorama Controls

    42/77

    Push Notifications Hands-on Lab

    1. Stop the debugging and return to the code. This step concludes theexercise.

    During this exercise you learned how to create an application withseveral pages using common controls, how to navigate between thepages and how to save and load page state information.

    Note: The complete solution for this exercise is provided at thefollowing location: Source\Ex1-Navigation\End.

    Page | 42

  • 8/3/2019 Using Pivot and Panorama Controls

    43/77

    Push Notifications Hands-on Lab

    Exercise 2: Introduction to Pivot

    ControlIn this exercise we continue to develop the Wazup application. At the end ofthis exercise the Wazup application will allow us to select a trend from thetrends page and see a list of tweets (Twitter messages) relevant to this trend,in addition to what we've accomplished in the previous exercise.

    The exercise will include the following tasks:

    Add Twitter page that uses a Pivot control

    Implement Twitter page functionality

    Task 1 Adding Twitter Page

    In this task we will add a placeholder page for Twitter functionality. Thepage will contain a pivot control that can display several pages ofinformation. We will use the pivot control on the next task to show apage of tweets for each trend in the trends list.

    During this task we will see how to add a new page that contains a pivotcontrol.

    1. Open Microsoft Visual Studio 2010 Express for Windows Phone fromStart | All Programs | Microsoft Visual Studio 2010 Express |Microsoft Visual Studio 2010 Express for Windows Phone.

    Visual Studio 2010: Open Visual Studio 2010 from Start | AllPrograms | Microsoft Visual Studio 2010.

    1. Open the Begin.sln starter solution from the Source\Ex2-Pivot\Begin folder of this lab. Alternatively, you can continue workingon the solution created in previous exercise.

    2. Add a folder to the project, named Themes. To do this right-click onWazup (project name) and select AddNew Folder

    Page | 43

  • 8/3/2019 Using Pivot and Panorama Controls

    44/77

    Push Notifications Hands-on Lab

    3. Add generic.xaml file to the Themes folder located in theSource\Assets\Themes folder in this lab.

    Figure 21Solution Explorer after adding the file generic.xaml to Themes folder

    1. Inside the folder Helpers, add a folder named LinkLabel.

    2. Add to the LinkLabel folder all the files from theSource\Assets\Helpers\LinkLabel folder of this lab. These shouldinclude Link.cs, LinkClickedEventArgs.cs, LinkCollection.cs,LinkLabel.cs and LinkMatchMethod.cs, which we are going to usein this exercise.

    Figure 22Solution Explorer after adding LinkLabel files

    1. Inside the folder Helpers, add a folder named WrapPanel.

    Page | 44

  • 8/3/2019 Using Pivot and Panorama Controls

    45/77

    Push Notifications Hands-on Lab

    2. Add to the WrapPanel folder all the files from theSource\Assets\Helpers\WrapPanel folder of this lab. These shouldinclude LengthConverter.cs, NumericExtensions.cs,OrientedSize.cs, TypeConverters.cs and WrapPanel.cs.

    Figure 23Solution Explorer after adding WrapPanel files

    1. Add a new item to the Views folder by right-clicking the Views folderand selecting AddNew Item

    Figure 24Add new item to the project

    Page | 45

  • 8/3/2019 Using Pivot and Panorama Controls

    46/77

    Push Notifications Hands-on Lab

    1. Select Windows Phone Pivot Page and name it TwitterPage.xaml.

    Figure 25Add new Windows Phone Pivot Page

    1. Open the file TwitterPage.xaml.cs.

    2. Replace the using section of the TwitterPage class with the followingcode snippet:

    (Code Snippet Using Pivot and Panorama Ex 2 Task 1 Step12 TwitterPage Using)

    C#

    using System;using System.Collections.Generic;using System.Collections.ObjectModel;using System.Windows;using System.Windows.Controls;

    using Microsoft.Phone.Controls;using Wazup.Services;

    Page | 46

  • 8/3/2019 Using Pivot and Panorama Controls

    47/77

    Push Notifications Hands-on Lab

    1. Add to the TwitterPage class two public static variables that will beused to pass information between the TrendsPage and TwitterPage.Use the following code snippet:

    (Code Snippet Using Pivot and Panorama Ex 2 Task 1 Step12 TwitterPage Static Variables)

    C#

    ////// Used to transfer the Trends collection between the trendspage and the twitter page///publicstatic ObservableCollection Global_Trends;

    ////// Used to transfer the current Trend between the trends pageand the twitter page///

    publicstaticTrend Global_CurrentTrend;

    1. Open the file TrendsPage.xaml.cs.

    2. Now we want to open the Twitter page when a trend gets clicked onthe trends page.To do that we will go back and implement theMouseLeftButtonUp event handler of the TextBlockTrend control.Our implementation will pass the trends collection and selected trendto the Twitter page by using static variables on the Twitter page.Replace the TextBlockTrend event handler of theMouseLeftButtonUp event with the following code snippet:

    (Code Snippet Using Pivot and Panorama Ex 2 Task 1 Step15 TwitterPage TextBlockTrend MouseLeftButtonUp Implementation)

    C#

    ////// Handles the MouseLeftButtonUp event of the TextBlockTrendcontrol.//////The source of the event.///The instancecontaining the event data.privatevoid TextBlockTrend_MouseLeftButtonUp(object sender,

    MouseButtonEventArgs e){ Trend trend = (sender asTextBlock).DataContext asTrend;

    this.GoToPage(ApplicationPages.Twitter);

    TwitterPage.Global_Trends = Trends; TwitterPage.Global_CurrentTrend = trend;

    Page | 47

  • 8/3/2019 Using Pivot and Panorama Controls

    48/77

    Push Notifications Hands-on Lab

    }

    1. Compile and run the application.

    2. Stop the debugging and return to the code. This step concludes the

    current task.

    Task 2 Implementing Twitter Page Functionality

    In this task we will implement the functionality of the Twitter page in theWazup application. At the end of this task the Wazup application willhave a working Twitter page.

    During this task we will use the Pivot control to show multiple pages ofdata, one page for each trend in the trends list. Each page in the pivotcontrol will show a list of tweets relevant to the page trend. We willalso see how to handle changes in the pivot selected page. When thepivot selected page will change we will load the current twits for the

    new page.1. Open the file TwitterPage.xaml

    2. Add the following XML namespaces to thephone:PhoneApplicationPage element next to the other XMLnamespaces definitions:

    XAML

    xmlns:localHelpers="clr-namespace:Wazup.Helpers"xmlns:localWindowsControls="clr-namespace:System.Windows.Controls"

    1. Set the DataContext property of the TwitterPage to be theTwitterPage itself. Do this by adding the following line to thephone:PhoneApplicationPage element:

    XAML

    DataContext="{Binding RelativeSource={RelativeSource Self}}"

    1. Now we will define the UI for the Twitter page. Locate the LayoutRootgrid and replace the content with the code below. The Twitter pagecontains two controls: a Pivot control that will show a different pagefor each trend and a ProgressBarWithText control that will show

    status information while loading tweets. The Pivot control is used toshow multiple pages which are easily navigated by flicking or panninghorizontally on the page. When you reach the last page of the pivotyou can flick once more to return to the first page. The Pivot controlitems are set via the property ItemsSource which is bound to acollection ofTrend items. To transform each Trend object into a validUI page, we use the ItemTemplate property, which defines the nameof the DataTemplate that will perform the transformation. We canalso control the look of the page header using the HeaderTemplate

    Page | 48

  • 8/3/2019 Using Pivot and Panorama Controls

    49/77

    Push Notifications Hands-on Lab

    property to define the name of the DataTemplate that will performthe transformation between a Trend object and the UI for the header.We will define the DataTemplate in the next step.

    (Code Snippet Using Pivot and Panorama Ex 2 Task 2 Step 4 TwitterPageLayoutRoot)

    XAML

    1. Here we define three data templates:

    TrendHeaderTemplate defines a DataTemplate thattransforms a Trend object into a TextBlockthat contains thetrend name. This template is used as the header for each itemin the Pivot control.

    TrendTemplate defines a DataTemplate that transforms aTrend object into the page UI for each item in the Pivot

    control. The page UI consists of a single ListBox control thatcontains the Twitter messages related to the trend. The UI forthe ListBox items is defined by the third data template namedTwitTemplate.

    TwitTemplate defines a DataTemplate that transforms aTwit object into a proper UI presentation of a Twitter messagethat includes an Image for showing the profile image of thetweet author, a LinkLabel control that shows the tweet textwith clickable links and two TextBlocks that show the tweetauthor name and tweet creation time.

    Add the following code into the TwitterPage resources section.

    (Code Snippet Using Pivot and Panorama Ex 2 Task 2 Step 5 TwitterPageResources)

    XAML

    Page | 49

  • 8/3/2019 Using Pivot and Panorama Controls

    50/77

    Push Notifications Hands-on Lab

    1. We now add buttons to the application bar in the Twitter page. Afterthe LayoutRoot grid ends, instead of the commented use of

    PhoneApplicationPage.ApplicationBar, add the following code:(Code Snippet Using Pivot and Panorama Ex 2 Task 2 Step 6 TwitterPage

    ApplicationBar)

    XAML

    Page | 50

  • 8/3/2019 Using Pivot and Panorama Controls

    51/77

    Push Notifications Hands-on Lab

    1. Open the file TwitterPage.xaml.cs

    2. Add the following dependency properties to the TwitterPage class:

    Trends of type ObservableCollection - used to savethe collection of Twitter trends

    CurrentTrend of type Trend used to save the currentlyselected trend

    Note: We implement an OnCurrentTrendChangedfunction in order to set the PivotControl.SelectedItemproperty with the current trend. The reason why we don't dothis by binding the SelectedItem property to theCurrentTrend property is due to a bug in the currentversion of the Pivot control for setting a new page that is"far" from the current page (not a neighbor) that might resultin an exception. Our code works around this.

    a. IsTwitsLoading of type bool used to indicate whether Twittermessages loading is currently in progress

    Use the following code snippet:

    (Code Snippet Using Pivot and Panorama Ex 2 Task 2 Step 4 TwitterPageProperties)

    C#

    #region Trends

    ////// Trends Dependency Property///publicstaticreadonlyDependencyProperty TrendsProperty =

    DependencyProperty.Register("Trends",typeof(ObservableCollection), typeof(TwitterPage), new PropertyMetadata((ObservableCollection) null));

    ////// Gets or sets the Trends property. This dependency property

    Page | 51

  • 8/3/2019 Using Pivot and Panorama Controls

    52/77

    Push Notifications Hands-on Lab

    /// indicates what are the current twitter trends.///public ObservableCollection Trends{ get { return

    (ObservableCollection)GetValue(TrendsProperty); } set { SetValue(TrendsProperty, value); }}

    #endregion

    #region CurrentTrend

    ////// CurrentTrend Dependency Property///publicstaticreadonlyDependencyProperty CurrentTrendProperty =

    DependencyProperty.Register("CurrentTrend", typeof(Trend),typeof(TwitterPage), new PropertyMetadata((Trend)null, newPropertyChangedCallback(OnCurrentTrendChanged)));

    ////// Gets or sets the CurrentTrend property. This dependencyproperty/// indicates what is the current trend.///publicTrend CurrentTrend{

    get { return (Trend)GetValue(CurrentTrendProperty); } set { SetValue(CurrentTrendProperty, value); }}

    ////// Handles changes to the CurrentTrend property.///privatestaticvoid OnCurrentTrendChanged(DependencyObject d,DependencyPropertyChangedEventArgs e){

    TwitterPage target = (TwitterPage)d; Trend oldCurrentTrend = (Trend)e.OldValue; Trend newCurrentTrend = target.CurrentTrend;

    target.OnCurrentTrendChanged(oldCurrentTrend,newCurrentTrend);}////// Provides derived classes an opportunity to handle changes tothe CurrentTrend property.///

    Page | 52

  • 8/3/2019 Using Pivot and Panorama Controls

    53/77

    Push Notifications Hands-on Lab

    protectedvirtualvoid OnCurrentTrendChanged(TrendoldCurrentTrend, Trend newCurrentTrend){ if (newCurrentTrend != oldCurrentTrend)

    {

    Dispatcher.BeginInvoke((Action)delegate{PivotControl.SelectedItem = newCurrentTrend;

    });}

    }

    #endregion

    #region IsTwitsLoading

    ///

    /// IsTwitsLoading Dependency Property///publicstaticreadonlyDependencyProperty IsTwitsLoadingProperty=

    DependencyProperty.Register("IsTwitsLoading", typeof(bool),typeof(TwitterPage), newPropertyMetadata((bool)false));

    ////// Gets or sets the IsTwitsLoading property. This dependencyproperty/// indicates whether we are currently loading twits.

    ///publicbool IsTwitsLoading{ get { return (bool)GetValue(IsTwitsLoadingProperty); } set { SetValue(IsTwitsLoadingProperty, value); }}

    #endregion

    1. Add a handler for the SelectionChanged event of the Pivot control.Here we respond to a page change in the Pivot control by searching

    for Twitter messages relevant to the new selected page. We do this bycalling the asynchronous method TwitterService.Search thataccepts a search text, a callback function to call when the Twittersearch is complete, and a callback function to call if the Twitter searchfailed, for example, the Twitter service is not available. If the Twittersearch completed successfully, we add the tweets to the Twitscollection of the current trend, which is bound to the page ListBox.

    Page | 53

  • 8/3/2019 Using Pivot and Panorama Controls

    54/77

    Push Notifications Hands-on Lab

    (Code Snippet Using Pivot and Panorama Ex 2 Task 2 Step 9 TwitterPagePivotControl SelectionChanged)

    C#

    privatevoid PivotControl_SelectionChanged(object sender,SelectionChangedEventArgs e)

    { if (e.AddedItems.Count == 0)

    { return;

    }

    Trend selectedTrend = e.AddedItems[0] asTrend;

    if ((selectedTrend.Twits == null) ||(selectedTrend.Twits.Count == 0))

    {IsTwitsLoading = true;

    } TwitterService.Search(selectedTrend.name, delegate(IEnumerable twits)

    {IsTwitsLoading = false;

    selectedTrend.Twits = newObservableCollection();

    foreach (Twit twit in twits){

    selectedTrend.Twits.Add(twit);}},

    delegate(Exception exception){

    IsTwitsLoading = false;});

    }

    Override the functions OnNavigateTo and OnNavigateFrom of the page.Use the StateManager class to save and load page state when the currentpage is changing. In the function OnNavigateTo, check whether theGlobal_Trends variable has a value; if it has, we know that the Twitter pagewas loaded after clicking a trend in the trends page.

    1. Otherwise, we assume that the Twitter page got loaded due to a returnto the application via the Backbutton, in which case we load theTrends information from the state object.

    (Code Snippet Using Pivot and Panorama Ex 2 Task 2 Step 10 TwitterPage State Handling)

    Page | 54

  • 8/3/2019 Using Pivot and Panorama Controls

    55/77

    Push Notifications Hands-on Lab

    C#

    private const string TrendsKey = "TrendsKey";private const string CurrentTrendKey = "CurrentTrendKey";

    protected override void

    OnNavigatedFrom(System.Windows.Navigation. NavigationEventArgs e){this.SaveState(TrendsKey, Trends);this.SaveState(CurrentTrendKey, CurrentTrend);

    }

    protected override voidOnNavigatedTo(System.Windows.Navigation. NavigationEventArgs e){

    if (Global_Trends != null){

    // get data from trends page, if we got from trends page

    Trends = Global_Trends;CurrentTrend = Global_CurrentTrend;

    }else{

    // get data from state objectTrends =

    this.LoadState(TrendsKey);CurrentTrend = this.LoadState(CurrentTrendKey);

    }}

    1. Add the following event handlers in the TwitterPage class. In thisstep we handle the application bar buttons. In each event handler weuse the Navigation class to go to the correct page. Note that the blogpage doesn't exist yet; it will be created later in this lab.

    (Code Snippet Using Pivot and Panorama Ex 2 Task 2 Step 4 TwitterPageEvent Handler)

    C#

    #region Appbar handlers

    ///

    /// Handles the Click event of the AppbarButtonDigg control.//////The source of the event.///The instancecontaining the event data.privatevoid AppbarButtonDigg_Click(object sender, EventArgs e){ this.GoToPage(ApplicationPages.Digg);

    Page | 55

  • 8/3/2019 Using Pivot and Panorama Controls

    56/77

    Push Notifications Hands-on Lab

    }

    ////// Handles the Click event of the AppbarButtonTwitter control.///

    ///The source of the event.///The instancecontaining the event data.privatevoid AppbarButtonTwitter_Click(object sender, EventArgse){

    NavigationService.GoBack();//this.GoToPage(ApplicationPages.Trends);

    }

    ////// Handles the Click event of the AppbarButtonBlog control.

    //////The source of the event.///The instancecontaining the event data.privatevoid AppbarButtonBlog_Click(object sender, EventArgs e){ this.GoToPage(ApplicationPages.Blog);}

    #endregion

    1. Compile and run the application.At this stage the Twitter page should work and look like the following:

    Page | 56

  • 8/3/2019 Using Pivot and Panorama Controls

    57/77

    Push Notifications Hands-on Lab

    Figure 26Twitter page showing tweets for a specific trend

    1. Stop the debugging and return to the code. This step concludes theexercise.

    During this exercise you learned how to use the Pivot control to showmultiple pages.

    Note: The complete solution for this exercise is provided at thefollowing location: Source\Ex2-Pivot\End.

    Page | 57

  • 8/3/2019 Using Pivot and Panorama Controls

    58/77

    Push Notifications Hands-on Lab

    Exercise 3: Introduction toPanorama Control

    In this exercise we continue to develop the Wazup application. At the end ofthis exercise the Wazup application will have a blog page that will show usposts from the Windows Phone Developer Blog, in addition to what we'veaccomplished in the previous exercises.

    The exercise will include the following tasks:

    Add a blog page that uses a Panorama control

    Implement Blog page functionality

    Task 1 Adding Blog Page

    In this task we will add a placeholder page for the Blog. The page will

    contain a panorama control that can show several pages ofinformation. We will use the panorama control on the next task toshow 4 different sub-pages of the blog page.

    1. Open Microsoft Visual Studio 2010 Express for Windows Phonefrom Start | All Programs | Microsoft Visual Studio 2010Express | Microsoft Visual Studio 2010 Express for WindowsPhone.

    Visual Studio 2010: Open Visual Studio 2010 from Start | AllPrograms | Microsoft Visual Studio 2010.

    1. Open the Begin.sln starter solution from the Source\Ex3-Panorama\Begin folder of this lab. Alternatively, you can continueworking on the solution created in previous exercise.

    Page | 58

  • 8/3/2019 Using Pivot and Panorama Controls

    59/77

    Push Notifications Hands-on Lab

    2. Add a folder to the project, named BlogImages by right-clicking onWazup (project name) and selecting Add New Folder.

    Figure 27Add new folder to the project

    1. Add to the BlogImages folder all the files which are located in theSource\Assets\BlogImages folder in this lab.

    2. Select all the files in the BlogImages folder and change the BuildAction property to Content.

    This will cause the images to be added to the XAP file instead of as resourcesinside the DLL file.

    Page | 59

  • 8/3/2019 Using Pivot and Panorama Controls

    60/77

    Push Notifications Hands-on Lab

    Figure 28

    Change Build Action for added blog imagesAdd a new item to the Views folder by right-clicking the Views folder andselecting AddNew Item

    Page | 60

  • 8/3/2019 Using Pivot and Panorama Controls

    61/77

    Push Notifications Hands-on Lab

    Figure 29

    Add new item to the project

    Select Windows Phone Panorama Page and name it BlogPage.xaml.

    Figure 30Add new Windows Phone Panorama Page

    1. Compile and run the application.

    Page | 61

  • 8/3/2019 Using Pivot and Panorama Controls

    62/77

    Push Notifications Hands-on Lab

    2. Stop the debugging and return to the code. This step concludes thecurrent task.

    Task 2 Implementing Blog Page Functionality

    In this task we will implement the functionality of the Blog page in the

    Wazup application. At the end of this task the Wazup application willhave a working Blog page.

    During this task we will use the Panorama control to show 4 sub-pages ofthe blog page.

    What distinguishes the Panorama control from the Pivot control is thatwhere the Pivot control shows multiple different pages, thePanorama control presents a single page divided to sub-pages thatwe can scroll, like a long horizontal canvas that extends the confinesof the screen. Unlike the Pivot control, the Panorama control has abackground image that stretches across all the sub-pages giving thefeel of a wide screen.

    1. Add reference to the System.ServiceModel.Syndicationassembly (from the Browse tab), located in\Source\Assets\Binaries\System.ServiceModel.Syndication.dll. This assembly is neededfor the blog service utility class that we will add shortly.

    Figure 31Add reference to System.ServiceModel.Syndication

    Page | 62

  • 8/3/2019 Using Pivot and Panorama Controls

    63/77

    Push Notifications Hands-on Lab

    1. Now we will add the utility classes used to work with the blogservice. Add the BlogService.cs, ImageItem.cs,ImageService.cs, and RssItem.cs files that are located inSource\Assets\Services folder of this lab to the Services folder .

    Figure 32Solution Explorer after adding blog service files into the Services folder

    1. Open the file BlogPage.xaml

    2. Add the following XML namespaces tophone:PhoneApplicationPage element next to the other XMLnamespaces definitions:

    XAMLxmlns:localHelpers="clr-namespace:Wazup.Helpers"xmlns:localWindowsControls="clr-namespace:System.Windows.Controls"

    1. Set the DataContext property of the BlogPage to be the BlogPageitself. Do this by adding the following line to thephone:PhoneApplicationPage element:

    XAML

    DataContext="{Binding RelativeSource={RelativeSource Self}}"

    Now we will define the UI for the blog page. Locate the LayoutRoot gridand replace the content with the following code. The blog pagecontains a single control: a Panorama control that will show 4different sub-pages. In the Panorama control we first define thebackground image. This background image will stretch across all thesub-pages of the Panorama control, giving the feeling of a wide

    Page | 63

  • 8/3/2019 Using Pivot and Panorama Controls

    64/77

    Push Notifications Hands-on Lab

    horizontal canvas which we will see section by section.Next wedefine the 4 sub-pages of the Panorama control:

    The first sub-page shows the last 5 blog posts The second sub-page shows all the posts in the blog The third sub-page shows all the comments in the blog

    The fourth sub-page shows a list of phone imagesThe DataTemplates we used in each of these sub-pages will be defined

    in the next step.

    (Code Snippet Using Pivot and Panorama Ex 3 Task 1 Step 5 BlogPageLayoutRoot)

    XAML

  • 8/3/2019 Using Pivot and Panorama Controls

    65/77

    Push Notifications Hands-on Lab

    ItemTemplate="{StaticResourceCommentTemplate}"

    />

    1. Here we define four data templates:

    PostLargeTemplate defines a DataTemplate that is used inthe "Last 5 Posts" sub-page. It transforms an RssItem objectinto a HyperlinkButton control that contains the title of thepost and navigates to the post when clicked, and a TextBlockthat contains the start of the post content.

    PostSmallTemplate defines a DataTemplate that is used inthe "All Posts" sub-page. It transforms an RssItem object into aHyperlinkButton control that contains the title of the post andnavigates to the post when clicked, and a TextBlockthatcontains the start of the post content.

    CommentTemplate defines a DataTemplate that is used inthe "Comments" sub-page. It transforms an RssItem object into

    a HyperlinkButton control that contains the title of thecomment and navigates to the comment's post when clicked,and a TextBlockthat contains the start of the commentcontent.

    ImageTemplate defines a DataTemplate that is used in the"Images" sub-page. It transforms an ImageItem object into anImage control that contains the loaded image and a TextBlockthat contains the image name.

    Page | 65

  • 8/3/2019 Using Pivot and Panorama Controls

    66/77

    Push Notifications Hands-on Lab

    Add the following code into BlogPage resources section.

    (Code Snippet Using Pivot and Panorama Ex 3 Task 1 Step 6 BlogPageResources)

    XAML

  • 8/3/2019 Using Pivot and Panorama Controls

    67/77

    Push Notifications Hands-on Lab

    Text="{Binding PlainSummary}"FontSize="20"

    MaxHeight="50"TextWrapping="Wrap" Margin="0"

    Foreground="White"

    />

    Page | 67

  • 8/3/2019 Using Pivot and Panorama Controls

    68/77

    Push Notifications Hands-on Lab

    1. We now add buttons to the application bar in the blog page. Afterthe LayoutRoot grid ends, add the following code:

    (Code Snippet Using Pivot and Panorama Ex 3 Task 1 Step 7 BlogPageApplicationBar)

    XAML

    1. Open the file BlogPage.xaml.cs

    2. Replace the using section of the BlogPage class with the followingcode snippet:

    (Code Snippet Using Pivot and Panorama Ex 3 Task 1 Step 9 BlogPageUsing)

    C#

    using System;using System.Collections.Generic;using System.Collections.ObjectModel;using System.Windows;using Microsoft.Phone.Controls;using Wazup.Services;

    1. Add to the BlogPage class the following dependency properties: LastPosts of type ObservableCollection - used to

    save the collection of last 5 posts Posts of type ObservableCollection - used to

    save the collection of posts Comments of type ObservableCollection - used

    to save the collection of comments

    Page | 68

  • 8/3/2019 Using Pivot and Panorama Controls

    69/77

    Push Notifications Hands-on Lab

    Images of type ObservableCollection - used tosave the collection of images

    IsPostsLoading of type bool used to indicate whether postsloading is currently in progress

    IsCommentsLoading of type bool used to indicate whethercomments loading is currently in progress

    Use the following code snippet:

    (Code Snippet Using Pivot and Panorama Ex 3 Task 1 Step 10 BlogPageProperties)

    C#

    #region LastPosts

    ////// LastPosts Dependency Property///publicstaticreadonlyDependencyProperty LastPostsProperty =

    DependencyProperty.Register("LastPosts",typeof(ObservableCollection), typeof(BlogPage), newPropertyMetadata((ObservableCollection)null));

    ////// Gets or sets the LastPosts property. This dependency property/// indicates what are the last posts.///public ObservableCollection LastPosts{ get { return

    (ObservableCollection)GetValue(LastPostsProperty); } set { SetValue(LastPostsProperty, value); }}

    #endregion

    #region Posts

    ////// Posts Dependency Property///public static readonly DependencyProperty PostsProperty =

    DependencyProperty.Register("Posts",typeof(ObservableCollection), typeof(BlogPage), newPropertyMetadata((ObservableCollection)null));

    ////// Gets or sets the Posts property. This dependency property/// indicates what are all the posts.

    Page | 69

  • 8/3/2019 Using Pivot and Panorama Controls

    70/77

    Push Notifications Hands-on Lab

    ///public ObservableCollection Posts{ get { return(ObservableCollection)GetValue(PostsProperty); }

    set { SetValue(PostsProperty, value); }}

    #endregion

    #region Comments

    ////// Comments Dependency Property///publicstaticreadonlyDependencyProperty CommentsProperty = DependencyProperty.Register("Comments",

    typeof(ObservableCollection), typeof(BlogPage), newPropertyMetadata((ObservableCollection)null));

    ////// Gets or sets the Comments property. This dependency property/// indicates what are the posts comments.///public ObservableCollection Comments{ get { return(ObservableCollection)GetValue(CommentsProperty); }

    set { SetValue(CommentsProperty, value); }}

    #endregion

    #region Images

    ////// Images Dependency Property///publicstaticreadonlyDependencyProperty ImagesProperty = DependencyProperty.Register("Images",typeof(ObservableCollection), typeof(BlogPage), newPropertyMetadata((ObservableCollection)null));

    ////// Gets or sets the Images property. This dependency property/// indicates what are the images.///

    Page | 70

  • 8/3/2019 Using Pivot and Panorama Controls

    71/77

    Push Notifications Hands-on Lab

    public ObservableCollection Images{ get { return(ObservableCollection)GetValue(ImagesProperty); } set { SetValue(ImagesProperty, value); }

    }

    #endregion

    #region IsPostsLoading

    ////// IsPostsLoading Dependency Property///publicstaticreadonlyDependencyProperty IsPostsLoadingProperty=

    DependencyProperty.Register("IsPostsLoading", typeof(bool),

    typeof(BlogPage), newPropertyMetadata((bool)false));

    ////// Gets or sets the IsPostsLoading property. This dependencyproperty/// indicates whether we are currently loading posts.///publicbool IsPostsLoading{ get { return (bool)GetValue(IsPostsLoadingProperty); } set { SetValue(IsPostsLoadingProperty, value); }

    }

    #endregion

    #region IsCommentsLoading

    ////// IsCommentsLoading Dependency Property///publicstaticreadonlyDependencyPropertyIsCommentsLoadingProperty =

    DependencyProperty.Register("IsCommentsLoading",typeof(bool), typeof(BlogPage), newPropertyMetadata((bool)false));

    ////// Gets or sets the IsCommentsLoading property. This dependencyproperty/// indicates whether we are currently loading comments.///

    Page | 71

  • 8/3/2019 Using Pivot and Panorama Controls

    72/77

    Push Notifications Hands-on Lab

    publicbool IsCommentsLoading{ get { return (bool)GetValue(IsCommentsLoadingProperty); } set { SetValue(IsCommentsLoadingProperty, value); }}

    #endregion

    1. Override the functions OnNavigateTo and OnNavigateFrom of thepage. Use the StateManager class to save and load page state whenthe current page is changing. In the function OnNavigateTo, we firsttry to load the values from the state object, then we check ifLastPosts has a value; if it doesn't, we load the data using theBlogService and ImageService functions. heBlogService.GetBlogPosts function accepts a callback function tocall if the posts loading id complete and a callback function to call ifthe posts loading failed, for example, the blog rss feed is currently

    down. BlogService.GetBlogComments work similarly. TheImageService.GetImages function returns a list of ImageItemobjects that represents an image.

    Use the following code snippet:

    (Code Snippet Using Pivot and Panorama Ex 3 Task 1 Step 11 BlogPageState Handling)

    C#

    privateconststring LastPostsKey = "LastPostsKey";private const string PostsKey = "PostsKey";privateconststring CommentsKey = "CommentsKey";

    private const string ImagesKey = "ImagesKey";

    protectedoverridevoidOnNavigatedFrom(System.Windows.Navigation. NavigationEventArgs e){ this.SaveState(LastPostsKey, LastPosts); this.SaveState(PostsKey, Posts); this.SaveState(CommentsKey, Comments); this.SaveState(ImagesKey, Images);}

    protectedoverridevoid

    OnNavigatedTo(System.Windows.Navigation. NavigationEventArgs e){

    // try to load data from state objectLastPosts =

    this.LoadState(LastPostsKey);Posts =

    this.LoadState(PostsKey);

    Page | 72

  • 8/3/2019 Using Pivot and Panorama Controls

    73/77

    Push Notifications Hands-on Lab

    Comments =this.LoadState(CommentsKey);

    Images =this.LoadState(ImagesKey);

    if (LastPosts != null){ return;

    }

    // if data wasn't loaded we get it from the blog serviceIsPostsLoading = true;

    BlogService.GetBlogPosts( delegate(IEnumerable rssItems)

    { constint NumberOfLastPosts = 5;

    LastPosts = newObservableCollection();Posts = newObservableCollection();

    foreach (RssItem rssItem in rssItems){

    IsPostsLoading = false;

    Posts.Add(rssItem);

    if (LastPosts.Count < NumberOfLastPosts){

    LastPosts.Add(rssItem);

    }}

    }, delegate(Exception exception)

    {IsPostsLoading = false;System.Diagnostics.Debug.WriteLine(exception);

    });

    IsCommentsLoading = true; BlogService.GetBlogComments( delegate(IEnumerable rssItems)

    {IsCommentsLoading = false;

    Comments = newObservableCollection();

    foreach (RssItem rssItem in rssItems){

    Comments.Add(rssItem);

    Page | 73

  • 8/3/2019 Using Pivot and Panorama Controls

    74/77

    Push Notifications Hands-on Lab

    }},

    delegate(Exception exception){

    IsCommentsLoading = false;

    System.Diagnostics.Debug.WriteLine(exception);});

    // load images from somewhereImages = new ObservableCollection();IEnumerable images = ImageService.GetImages();

    foreach (ImageItem imageItem in images){

    Images.Add(imageItem);}

    }

    1. Add the following event handlers in the BlogPage class. In this stepwe handle the application bar buttons. In each even handler we usethe Navigation class to go to the correct page.

    (Code Snippet Using Pivot and Panorama Ex 3 Task 1 Step 12 BlogPageEvent Handler)

    C#

    #region Appbar handlers

    ////// Handles the Click event of the AppbarButtonDigg control.

    //////The source of the event.///The instancecontaining the event data.privatevoid AppbarButtonDigg_Click(object sender, EventArgs e){ this.GoToPage(ApplicationPages.Digg);}

    ////// Handles the Click event of the AppbarButtonTwitter control.///

    ///The source of the event.///The instancecontaining the event data.privatevoid AppbarButtonTwitter_Click(object sender, EventArgse){ this.GoToPage(ApplicationPages.Trends);}

    Page | 74

  • 8/3/2019 Using Pivot and Panorama Controls

    75/77

    Push Notifications Hands-on Lab

    ////// Handles the Click event of the AppbarButtonBlog control.//////The source of the event.

    ///The instancecontaining the event data.privatevoid AppbarButtonBlog_Click(object sender, EventArgs e){

    // Set "last 5 posts" as default item// this has the side effect of changing the selected itemPanoramaControl.DefaultItem = PanoramaControl.Items[0];

    }

    #endregion

    1. Compile and run the application.

    Page | 75

  • 8/3/2019 Using Pivot and Panorama Controls

    76/77

    Push Notifications Hands-on Lab

    2. At this stage the blog page should work and look like the following:

    Figure 33Blog page showing blog posts

    1. Stop the debugging and return to the code. This step concludes theexercise and the lab.

    During this exercise you learned how to use the Panorama control to show

    a wide page with several sub-pages.

    Note: The complete solution for this exercise is provided at thefollowing location: Source\Ex3-Panorama\End.

    Summary

    Page | 76

  • 8/3/2019 Using Pivot and Panorama Controls

    77/77

    Push Notifications Hands-on Lab

    During this lab you learned about the new controls in Windows Phone 7 forpresenting information, Pivot and Panorama. You also learned how tonavigate between the application pages and how to handle page stateinformation when your page gets navigated away to a different application.