01. WP8 development Basics

Source: Internet
Author: User

1. WP application Lifecycle

To write a WP program, you must first understand the life cycle of the program, because we need to do some necessary things at these different points of time, such as saving and restoring some data. We must pay attention to the following events.

Applicatoin_launching: triggered when the program is started.

Application_closing: triggered when the program exits.

Application_activated: It is triggered when the program returns to the application by navigating forward. Or triggered when the program is activated again after it is sleep. Note: When this event is triggered, the program is restored, rather than re-opened.

Application_deactivated: triggered when you navigate from this page to another page or press the main menu key. Indicates that the page is not active, but the program does not exit.

2. page navigation

  • Use the hyperlinkbutton Control for navigation. You can migrate to the relevant page by setting the navigateuri attribute of hyperlinkbutton. Note that the URI must start with a left slash.
<Hyperlinkbutton content = "My music" navigateuri = "/music. XAML/>
  • Navigate through the background code. All pages are inherited from the page class. This class has a navigationservice member used for navigation between pages. we can add a button on the page and click the handwritten code in the event to navigate.
private void Button_Click(object sender, RoutedEventArgs e)        {            this.NavigationService.Navigate(new Uri("/Sub/Photo.xaml", UriKind.Relative));        }

3. page navigation events

There are three events related to page navigation: onnavigatedfrom, onnavigatedto, and onnavigatingfrom. They are all page-protected methods. We can rewrite these methods on our own pages. Onnavigatingfrom and onnavigatedfrom are triggered before and after leaving this page. onnavigatedto is executed when other pages are migrated to this page. For example, if there is a main homepage and a sub-page, the trigger order for migrating the home page to the sub-page is as follows:

Onnavigatingfrom (main)-> onnavigatedfrom (main)-> onnavigatedto (sub)

4. data transmission between pages

We have already talked about how to migrate between pages. What should we do if we need to transfer some data during the migration? In WP8, The get value transfer method is similar to that on the web page. After the URL string, add? Key1 = value1 & key2 = value2: Use Key-value pairs. Separate key-value pairs. In the onnavigatedto method on the migration page, we can obtain these values through navigationcontext. querystring of page.

For example, we can slightly modify the hyperlinkbutton on the home page:

<Hyperlinkbutton content = "My music" navigateuri = "/music. XAML? Id = 100 & amp; type = 2 "type = 2" type = "codeph" text = "/codeph"/>

Note: In XAML, The & symbol must be escaped as & amp;. If it is in the background code, no escape is required.

You can obtain the passed value in the onnavigatedto method of the child page.

protected override void OnNavigatedTo(NavigationEventArgs e)        {            var id = this.NavigationContext.QueryString["id"];            Debug.WriteLine("id=" + id);            base.OnNavigatedTo(e);        }

5. Uri ing

Uri ing simplifies the transmission of parameters between pages, especially when there are many parameters. For example, we need to migrate to this page/SUB/photo. XAML? Type = {type} & id = {ID}. Can we write the form/SUB/{type}/{ID? Through URI ing, we can define this ing when the application is initialized, so that the system can identify the translation ing. The app class defines a static phoneapplicationframe variable rootframe, which is the root Framework of the application. This ing can be defined by setting the rootframe. urimapper attribute. Therefore, the specific method is to add a ing setting method in the app class and call it in the app constructor.

/// <Summary> /// set URI ing /// </Summary> private void seturimapping () {If (rootframe! = NULL) {urimapper = new urimapper (); urimapping = new urimapping (); // set the matching mode urimapping. uri = new uri ("/SUB/{type}/{ID}", urikind. relative); // set the actual URI urimapping. mappeduri = new uri ("/SUB/photo. XAML? Type = {type} & id = {ID} ", urikind. Relative); urimapper. urimappings. Add (urimapping); rootframe. urimapper = urimapper ;}}

In the migration code, we can write as follows:

private void Button_Click(object sender, RoutedEventArgs e)        {            this.NavigationService.Navigate(new Uri("/Sub/2/100", UriKind.Relative));        }

You must use the type and ID parameter names in the subpage to obtain the corresponding values.

6. forward and backward in the navigation bar

The mobile phone's rollback key allows us to perform the rollback operation. We can also perform backward or forward navigation through the Goback and goforward of navigationservice. If there is no page to navigate to, calling these two methods will cause an exception. We can query whether navigation is possible through the cangoback and cangoforward attributes.

private void HyperlinkButton_Click(object sender, RoutedEventArgs e)        {            if (this.NavigationService.CanGoBack)            {                this.NavigationService.GoBack();            }        }

For the mobile phone's return key, we can block it by code so that it does not work, but it is generally not recommended to do so. Override the onbackkeypress event and set E. Cancel = true;

protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)        {            base.OnBackKeyPress(e);            e.Cancel = true;        }

When we move forward or backward, the browsing history is pushed into the backstack of navigationservice. This is a stack first in and then out. We can remove these history records, but only one record can be removed at a time, after removal, the removed page records will be skipped when you roll back.

if (this.NavigationService.CanGoBack)            {                this.NavigationService.RemoveBackEntry();            }

7. Save and restore the application status

If the application is restored from sleep state, the data is maintained by the system and will not be lost. If the application has been logically deleted (in the tombstone status), you need to manually restore the data. The application_launching event will not be called when the logical deletion is restored. We need to restore the data in application_activated and save the data in application_deactivated, while the data is saved in the dictionary variable phoneapplicationservice. Current. state.

// Code executed when the application is disabled (sent to the background) // This Code does not run private void application_deactivated (Object sender, deactivatedeventargs e) when the application is disabled) {// save application data if (! String. isnullorempty (appdata) phoneapplicationservice. current. state ["mydata"] = appdata;} // activate the application (on the frontend) code executed // This code is not executed when the application is started for the first time private void application_activated (Object sender, activatedeventargs e) {// restored from sleep, no special if (E. isapplicationinstancepreserved) return; If (phoneapplicationservice. current. state. containskey ("mydata") appdata = phoneapplicationservice. current. state ["mydata"] as string ;}

Note that the stored data must support serialization. You can use isapplicationinstancepreserved to check whether the program has been restored from its sleep state. For the debugging of the tombstone status, you can set the properties of the project and select debugging -- execute logical deletion when debugging and stopping.

7. Save and restore the Page Status

The status of this application is similar, but the scope of the application is this page. When the program recovers from the tombstone status and then returns to the page, because the operating system does not retain the data status, when we perform page navigation, the status data of the current page should be saved as much as possible. Save the status in onnavigatedfrom on the page and restore it in onnavigatedto. The status data is stored in the state variable of the page.

protected override void OnNavigatedFrom(NavigationEventArgs e)        {            State["Name"] = this.lblName.Text;            base.OnNavigatedFrom(e);        }        protected override void OnNavigatedTo(NavigationEventArgs e)        {            if (isNewPage)            {                this.lblName.Text = State["Name"] as string;            }                      base.OnNavigatedTo(e);        }

When the tombstone status is restored, the app and page constructor will be called, so we can determine whether to restore data from whether the page constructor is called.

01. WP8 development Basics

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.