Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

03.Controls in Windows Phone

Windows Phone 8 progamming

  • Be the first to comment

  • Be the first to like this

03.Controls in Windows Phone

  1. 1. Building Windows Phone Applications W Nguyen Tuan [ Microsoft Certified Trainer
  2. 2. Agenda - Page navigation - Application Bar - Page Orientation - Screen Resolutions - Localization - Windows Phone Toolkit - Page Transitions
  3. 3. Page Navigation
  4. 4. Frame and Page - Frame - Topvlevel container control - PhoneAppli tionFrame class - Contains the gage control and system elements suc as system tray and application bar - Page - Fills entire content region of the frame - PhoneApplicationPagevderived class - Contains a title - Optionally surfaces its own application bar
  5. 5. Page Navigation - XAML apps on Windows Phone use a . main page second page page-based navigation model ~ Similar to web page model - Each page identified bya um ~ Each page is essentially stateless »l. .ii_. al. _is. , H‘ Faun pnl/ ate Void Hyper‘linkButton_Cl1(k_1( objett sender, Rout0dEvCntAr‘g5 e) ( Navigationservite. Navigate( new Ul‘1("/ Sc-(ondPage. xaml", Ul‘1K1nd. R2lati/2)); }
  6. 6. Navigating Back ' Application can provide controls to navigate back to preceding page lmainl page ; ecdnd page private void Eutton_C1ick_1( object sender, RoutedEventArgs e) { Navigationservice. GoEack(); } ' The hardware Back key will also navigate back to preceding page - No code required — builbin behaviour
  7. 7. Overriding Back Key - May need to override Back hardware key if 'back to previous page’ is not logical behaviour ‘ For example, when displaying a popup panel - User would expect Back key to close the panel, not the page
  8. 8. Overriding the Back Key <phL7ne PhoneAppli(atiunPage x: Clas5="PhnneApp1.MainPage" shell : Sy5temTray . Isvisilzle rue" Bacl<KeyPFess= "PhaneApp1icatianPage_EackKeyPr*ess"> m code private vnid PhaneApp1icatianPage_EackKeyPr‘ess(abject sender, system. campanenmade1.(ance1EventArgs e) ( e. cance1 = true; // Tell system we‘ve handled it / / Hide the popup. ..
  9. 9. Passing Data Between Pages - Can pass string data between pages using query strings private ma passParam_(1i(k(abje(t sender, mmeasvenurgs 2) { ) Navigatiunservite. Navigate(new Uri("/ Se(L7ndPage. xamlPmsg= “ . textfiuxllext, UriKirm. Re1ative)); - on destination page prutetted override void UnNavigatedTL7(SystemMinduwsNavigation. Navigat1unEvenlArgs 2) { base. UnNavigatedTu(e); string querystringvalue = if (NavigatiL7n(ontext. Quer)/ String. TryGetValue("msg", nut querystringvaluen textE1u(kl. Text = querystringvalue;
  10. 10. Passing Objects Between Pages - Often, you will pass a data object from one page to another - E. g., user selects an item in a list and navigates to a Details Page - One solution is to store your ViewMode| (that is, data) in vourApp class - Global to whole application - Pass the ID of the selected item in query string / / Navigate to the new page Navigationservice. Navigate(new Ur‘1("/ Detail5Page. xaml?5ele(tedItem: " + (maintangtistselemzr. se1ected1tem as ItemV1ewModol). ID_, Ur‘JKJnd. Re1ative));
  11. 11. Handling Non Linear Navigation - Desi n your app navigation strategy care ullyl - If you navigate from 'third page’ to 'main age’ and your user then presses the Back ey, what happens? - User expects app to exit - App actually navigates back to Third Page - Solution for Windows Phone 7.0 was complex code to handle back navigation correctly or the NonALinear Navigation Recipe lilarary from AppHub - Windows Phone APls: - Navigationservice. RemoveBackEntry() Nonlinear Navigation (A Loop)
  12. 12. Navigationservice. RemoveBackEntry() - when ‘Third Page’ navigates hack to MainPage, put a marker in the query string uavigationsenvice. Navigate(new Ur‘1("/ MainPage. xaml? homeFromThird: true"_, Ur‘1K1nd. Re1ative)); - In OnNavigatedTa() in MainPage, Iaakfar the marker and if present, rernovethe ' Third Page’, ’Sei: undPage' and uriginal instance af ’MainPage'fmm the navigatiun history stack protected override vnid 0nMavigatedTn(Na/1gatJonEvontAr‘gs e) ( if (e. NavigatianMode . system. winiiows. iiavigatian. NavigationMoae. ~e» as Navigat)nnCantext. Quer*yString. CantainsKey("homeFrL7mThird")) ( Mavigatianservice. RemaveEackErItr‘y()5 / / Remove ThirdPage Mavigatianservice. Remaveaaci<Entry(); // Remove Se(nndPage Mavigatiansenvice. Remaveaaci<Entry(); // Remove original Mainvage ) base . onuavigatetno(e);
  13. 13. Demo NavigationApp
  14. 14. A~'; r«', f~fu‘h<: :art: ‘h<: :>-m Eta r
  15. 15. Application Chrome System Tray and Application Bar System Tray System owned indicator area that displays system-level status information Apps can show/ hide Microsoft. F'hone Shell. Sys| emTray. |sVisib| e = false, Lullnlcllevlllrel Application Bar Area where applications can display buttons for the most common tasks Can display pap—up menu for less common tasks
  16. 16. iii. :10 Use the ApplicationBar instead of creating your own menu system choose & Search Up to 4 buttons plus optional menu Swipe up the bar to bring up the menu Don’t fill all 4 slots if not needed Swipe up the bar to bring up the menu Use white foreground on transparent background for icons System will colorize button according to users selected theme
  17. 17. App| icationBar in Xaml (phone: vmnenppxmuamge M1333: (Rl<app. l<a1nVage" > <phanetPhoneApp1i<aUanPage. App1itaunnaan <she11:App11<auanBar x: Mame= "AppBar" apmzy (shell: App11:aUanBar. Bu(mns> <shelltnppliatinnaarltanauunn xtuame 1.9" Isl‘IermEnab1ed= "rrue"> eufianzaclauzzan" I<onUM= "Images/ appbarmeu. resnpng" Text 'Me«"(11:k 'Meufianlatzautmn_(11<k"/ > <shelltAppntaunnaarltanauunn xtrlame earchautm - Imnur Images/ appbar. feature. sear<h. res(. png" Text -ma" cm SearchBu((nn_(1i<k"/ > </ shelltAppM<auanBar. Buuans> (shell : App1muansar. nenme«. s> <shelltnpplkatinnaarnenulteon xtname (nu. <shelltnppntaunnaarnenultem xtname um 'Genera(el<ermI(em rm ‘Generate om enera(e41ermI(em_(11<k" / > '(1eamermI(em" fax! -near om 1earnenme«. _c1m< / > </ she]1tAppli: auanBar. >1ermIzems> </ she11tApp11:auanBar> </ phanet PhanenpplitauanPage. AppM: auanBar> </ phone: PhaneApp1i: aUmwPage>
  18. 18. Application Bar and Landscape ApplicationBar‘ paints on side of screen in landscape Has built-in animation when page switches orientation ww ‘Contacts ‘.17[‘“77'~Y t
  19. 19. Eohtacis Cams/ us’ )4! If Application Bar opacity is less than 1, displayed farvnll . . page will be the size of the screen Application Bar m, ,m overlays screen content W Eamn If Opacity is 1, displayed page is resized to the area ""‘"‘ of the screen not covered by the Application Bar 1 i,
  20. 20. App| icationBar Design in Blend — and now in VS Too! ¢. ».. ¢mmm. Iulwm ‘I I
  21. 21. Demo App| icationBar
  22. 22. Handling Screen Orientation Changes
  23. 23. Phone Ul Design — Orientation u : --c-poi . ... ... ... ... :: .‘: :.": ':. .". -.'. ':. "="' . .a2._ . ..-«.1-an---. ... ._. I‘ I -5 I ; I l :31 . ._. ... .., ... ... .. . ... .—---. ... ..n. -. - This application does not work in landscape mode at the moment - Not all applications do, or need to - You can configure applications to support portrait or landscape
  24. 24. New Device Tab in Visual Studio 2012 - View Designer in Portrait or Landscape . ‘m[: :| .1» . - H
  25. 25. Selecting Orientations Suppor‘ted0r‘ientations= " Portrait" Supported0rientations= "Portrait0rLandscape" - A XAML property forthe phone application page lets you select the orientation options available - Your application can bind to an event which is fired when the orientation changes
  26. 26. Layout May Need Altering Layout unaLtered reaps Layout optimised for Landscape
  27. 27. Using a Grid to Aid Landscape Layout i <phone: PivotItem Heaae <5rid> <Grid. ColumnDefinition5> <ColumnDefinition width <ColumnDefinition width Autn"/ > </ Grid. ColumnDefinitions> <Grid. RowDefinition5> <RowD2finition Hugh <RowDefinition Hugh <RowD2finition Hugh <RowDefinition Hugh </ Grid. RowDefinition5> ecipe"> </ Grid> - In the Grid, the second column is unused in Portrait
  28. 28. Move Elements in Landscape Layout <phone: PivotItem Heade <Grid> <Grid. ColumnDefinitions> <ColumnDefinition width <ColumnDefinition budth Autn"/ > ecipe"> </ Grid. ColumnDefinitions> RW0 <srm. Rowner1h1uohs> . <RowDefinition Hugh " " lf. “&"&“. ’:. ‘.5.T, ‘:fi$. , Rowl <RowDefinition Hugh "”“""“""""""““‘"" ' <RowDefinition Hugh Km <RowDefinition Hugh Rm, ” </ Grid . Rownefinitions > </ Grid> - In Landscape, the recipe description moves into the second row and the second column and the third row ofthe grid is now unused. Since that row’s Height is u * u , it shrinks to zero.
  29. 29. Moving Elements private / aid PhuneApp1icatiunPage_Or*ientatiunChanged(abject sender, Orlentat1onChangodEvontArgs e) ( if (thisfirientatiun ( Pafieorientation. LandscaDeLeFt H thisfirientatian Pageonentauon. LandscapeRignt) Directiunsscrallvievwer. SetValue(Gr1d. RuwPruperty, 1); Directiunsscmllviewer. setva1ue(arm. culumnvruperty, 1); } else ( Directiansscrullviewer. SetVa1ue(Gr1d. RuwPr'uDerty, 2); Directiunsscrullviewer. SetVa1ue(Gr1d. Cu1umnPraperty, a); }
  30. 30. Demo Landscape Orietation
  31. 31. Supporting Multiple Screen Resolutions
  32. 32. Multiple Resolutions VVVGA 480x800 “Inc 27 VVXGA 768x12BD )7 720p 720x1280 1 Wm“ V. ..
  33. 33. Multiple Resolutions — Scaling & Touch WVG/ 720;: 480x800 7Z0><lZ8O
  34. 34. So I Have to Do Three Different Uls? - Well, No. .. - As developers, we work with device independent pixels - 05 applies a scale factor to the actual resolution Resolution Aspect lauo Scale Factor Scaled resolution WVGA 800x430 15:9 1.oxseale 800x48/J WXGA 1zlwx7ss 15:9 Lsxseale lwoxalw 1.5x seale, ao plxalstaller 72°” 1"” " 72° 1” (53 pixels, before sealing) 853x48/.7
  35. 35. Scaled Resolutions WVGA
  36. 36. Use ”Auto” and ”*” on Grid Rows To Ensure Good Layout - Set Grid Row Height to "Auto" to size according to the controls placed within it (Gm, _ _ <Gr*id. RowDefinition5> - Set Grid Row Height to "*" to take <xume«; n;t; un Height -' a"/ > "P 3" the rest 0f the Space Ziifiiiilfiiil 33:2; Au: ::"/ > . If you size multiple rows using 11*", </ Gr*id. RowDefinition5> available space is divided up </ mm evenly between them
  37. 37. Adaptive Layout Using Grid recxpe Image hevghtsuzed explicitly at 240px Durectvons row vs "‘" so gets everything that’; left — ends uptaller on 720p aouom row Is "Auto" so sued to hold a Temilock
  38. 38. Images - In most cases, you should supply images targeting the WXGA (1280 x 768) screen - WXGA assets are of the highest quality - will automatically scale down on WVGA phones - Still look great on 720p (1230 x 720) - If you want, you can include images at each of the three resolutions in your project - E. g. Mylmage. wvga. png, Mylmage. wxga. png and Mylmage.720p. png - At runtime, get Application . Current . Host . Content . Sca1eFactor to determine the resolution ofthe screen on the current phone, returns 100for WVGA, 150for WXGA and 150 for 720p - write code to load image at runtime appropriate for the current screen resolution
  39. 39. Splash Screens - To add a splash screen to your project suitable for all resolutions, add a file as content called Sp| ashScreen| mage. jpg at 768 x 1280 resolution I The framework automatically scales it to the correct size on different resolution screens - If you want to provide pixe| —perfect splash screens for all resolutions, add images with the following names: - SpIa5hScreen| mage. Screen-WVGA. jpg - SpIa5I15creen| mage. Screen-WXGA. jpg - SpIa5hScreen| mage. Screen-72013.jpg ° In addition to these images, you must still include the default Sp| ashScreen| mage. jpg file
  40. 40. App Icon and Tiles - You must supply app icon and tile images sized for WXGA - The framework automatically scales to the correct size for WVGA and 720p Tile size WXGA Application Icon 100 x 100 Small 159 x 159 Medium 336 x 336 Large 691 x 336
  41. 41. Introduction to Localization
  42. 42. Language Support - Windows Phone 8 supports 50 display languages (shipped with the phone depending on market and country/ region) and selectable by the user on the | anguage+region section ofthe Settings page - Windows Phone 7.1 supported only 24 - Windows Phone 8 allows you to build apps that read from right to left http. //msdn microsoft com/ en- u5/Iibrary/ windowsphone/ develop/ ff637520(v: vs 105) aspx | anguage+regi
  43. 43. New Project Templates Have Localization Support Built In - Every new project you create in Visual Studio 2012 has a class included called Localizedstrings - Simply pmvides programmatic accessto resources - An instance or this is create in App. xaml in the Application Resources with the key Loalioedstrings - Every new project also includes a resources file: ResourcesAppResources. resx - some strings already defined in here - create allyour stringliterals in hereto support localization - All new projects also included commented-out code in MainPage. xam| .cs to setup a localized Application Bar
  44. 44. Accessing String Resources from XAML um um Iindmg vo» Nexllhdl In: 7 I - Databind the Text property of »—{-~»= wrw- _ your TextB| ock and other page na controls to the Statickesource with a key of design one Localizedstrings -That is an instance ofthe Localizedstrings class - It provides access to string resources design two design three
  45. 45. Add Support for Additional Languages - Double-click project properties to open the Properties editor - On the Application tab -' -Check each ofthe ' j languages your app j will support - Save the Project Properties -Visual Studio creates new AppResou rces files for each ‘ selected language/ culture ‘T
  46. 46. Translate the Additional Languages Resource Files - Visual Studio adds a resource file for each additional language that the app will support. Each resource file is named using the correct culture/ language name, as described in Culture and language support for Windows Phone in the documentation - For example: - For the culture Spanish (Spain), file is AppResources. es-ES. vesx. - For the culture German (Germany), file is AppResources. de-DE. vesx. - Supply appropriate translations in each resource file
  47. 47. Define the Default Language - Doub| e—c| ick WMAppManifest. xm| to open the manifest editor - On the Packaging tab i - Set the Default Language to the language of your default resources - This identifies the language of the strings in the default resources file. For example, if the strings in the default resources file are English (United Kingdom) Ian ua e strings, you would select Eng ish United Kingdom) as the Neutral Language for the project
  48. 48. Demo Animalsound
  49. 49. The Windows Phone Toolkit
  50. 50. WPToo| kit - A product ofthe Microsoft Windows Phone team - Formerly known as the 'Si| ver| ight Toolkit’ - The Windows Phone Toolkit adds new functionality 'out of band’ from the official product control set - Includes full open source code, samples, documentation, and design- time support for controls for Windows Phone - Refresh every three months or so - Bug fixes - New controls
  51. 51. How to Get the Toolkit - httQ: ([Qhone. codeg| ex. com - Get source code, including the sample application - No MSI! — Install binaries from NuGet only Pin
  52. 52. NuGet - Package management system for . NET - Simplifies incorporating third-party libraries - Developer focused - Free, open source - NuGet client is included in Visual Studio 2012 — including Express Editions! - Use NuGet to add libraries such as the Windows Phone Toolkit to projects
  53. 53. Controls in the Windows Phone Toolkit
  54. 54. ContextMenu pm to sum menu ‘ dflete share
  55. 55. DatePicker and TimePicker
  56. 56. Toggleswitch
  57. 57. WrapPane| <: :mJku ‘drip! -‘anal Czuncitn — HI: :Aznn: iJ"> zw nexgh: "10.’ S: :2k Black" , > ma" 5:: xa= "E]ack" / > " smx ax ''E]a: x'' , » <; len: pa*‘; le m1 'E1ue” -m-. (Jena 4;]: <REc Ele (Jana-:1: <REcu- 112 <. len: r.a"q1e _ )1="3:a: qe A: m.= ~mu- Hugh <R2: 712 11 "Teal" 3:; am nigh: no <;1eI: r.a. ".q1e ma" Hem? B1a: k" ‘> <12:ca gle axe an 'Kagenr. a" Hxdc. Slack’ / > xApEAna]> wrap panel
  58. 58. ListPicker - WP7 ComboBox - Dropdown list for small number of items L-isltPlcl<er LlstPlcl<er - Full screen selector for longer lists
  59. 59. .. .And Many More - Custom MessageBox - Rating control - AutoComp| eteBox - ExpanderView - HubTi| e - . .‘more. .‘ - Download the source from htt : Silverli ht. code | ex. com, build the sample application and deploy to emulator or device
  60. 60. Page Transitions and Ti| tEffect
  61. 61. Page Transitions - Easy way to add page transitions to your app similar to those in the bui| t~in apps - Different transitions are included - Roll, Swivel, Rotate, Slide and Turnstile W, - Start by using the TransitionFrame control from the ‘ . .;, ... Windows Phone Toolkit instead of the default Q PhoneApp| icationFrame - Set in Initia| izePhoneApp| ication() method in App. Xam| .cs: / /RoatFrame = new PhoneApplicationFrame(); RootFrame : new Tr‘ansitionFr‘ame();
  62. 62. Enabling Transitions on a Page - Declare namespace for windows Phone Toolkit assembly zvhun . .. u hant. 'u7Dh: a1onPage (I/ ’ . u.-(xm. ... sp. « M1<'nsal(. Phun: (anvolz; sselibly-Mi<>asuV(. PVmn: .(ont*c]s. Vca]kxr" - Under <phone: PhoneApp| icationPage> root element, add transition you want (main: Vvunsl2tanservi(e. Navigation! nn~anslzlun> ltoallul l4AvgAtianInYran6|tion> «mm Navlzaum-Inlransn1an. t?A(kwavd> uxmllul m. - t. i.. n-. ... ».uu. . ackwawchi / > </ twun NA»/ gat| onInTr'an§1ton. l'la: kuard> (mum Navlznmy-lnIrans| unn. >w am: (mun m. »m. i.. n». .i. »ui. m arwardh / » m. .., u.u Na»/ g4(IKmlnYv'. m~l4m. VUH4M'd> </ worm N. wxg. Ixonlnlixvnsxlmm </ lnnlkll mmuim. rvuv. mmi. m.m. umi. ..» uxmllil m. ..u. .,. .s vluv u mmaumm-. .n. ,.. ... n unnlkn | v; ;.1(Inn| hIlh n. ,n. ..m unnlklv >4. malmvniluilrnunllliui‘l1.ukw‘Irfl> nmrlknl in. ..»t. i.m. ..ui. ... . MW-. >o. .x x» (lloolkxl Nuvx lm(Nlli' 5.. .“. .t. ... ... i) . .m. im >4. . ..m. u.. u v| s|l| i)Auli)m. <|i'iI7 uuvlkll hilv-Vlllvl . .». u.m arwnrdfiuz / > </ lna| k)l mm; llnivbullimiaxlluv . .. . .-. i> </ n.. .u. t miwu Hull . <|v~lI| m>> </ luulhl li«Mnmnfirrvur. N.wxgal4m0u(YAnn«| (|nn>
  63. 63. Ti| tEffect - Add additional visual feedback for control interaction - Instead of simple states such as Pressed or Unpressed, controls with Ti| tEl"fect enabled provide motion during manipulation - For example, Button has a subtle 3D effect and appears to move into the page when pressed and bounce back again when released - Easy to enable Ti| tEf'fect for all controls on a page mm P7on: N>DJ)(auovil‘agu xmlns rooikn= "z]r rvamespate M1cr'osoflJ’hone (onkrals, issnlwblyri-ixzrosuft Phone (antral; Vonlknt" mun ILHEVVELK IsnkEn4n1ed: "rme"> doggleflutton iii'»i‘= "B|1t‘DV" - V «ii -' , :"1r*ue"/ >
  64. 64. Demo PhoneToo| kitSamp| e
  65. 65. Review Navigation to pages is performed on the basis ofa URI (Uniform Resource Indicator) values The back button normally navigates back to the previous page, but this can be overridden The URI can contain a query string to pass contextual string data Support for Localization is incorporated into the project templates §upportin different screen resolutions is simplified because they are scaled to a near- identical e ective resolution. Supply images scaled for WXGA and they will be scaled down automatically for lower screen resolutions. The Windows Phone Toolkit is an out of band method for Microsoft to release additional tools and libraries outside of Visual Studio release cycles I http [[ er| ight. codep| ex. com The toolkit includes Pa e transitions and Ti| tEffect with which you can add common animations to your app ications