Three data sharing methods for Windows Phone (8)

Source: Internet
Author: User


This section describes how to implement data sharing. First, two pages are created. When the mainpage is navigated to the secondpage through the event, we need to pass some content in the mainpage (such as a string) to the secondpage, And the secondpage page shows the passed content. When the page secondpage is navigated to the mainpage through the event, we also pass some content (such as a string) to the mainpage;

In the created mainpage. XAML file, I added only one button element, set the displayed content, and defined the touch events of the element:

<Button X: Name = "BTN" content = "navigate to the second page" grid. Row = "1" Click = "btn_click"> </button>

The following namespace must be referenced in the hidden file of mainpage:

// Reference the namespace -- used by the phoneapplicationservice class
Using Microsoft. Phone. shell;

The code for the hidden mainpage file is as follows:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
// Reference namespace-used by PhoneApplicationService class
using Microsoft.Phone.Shell;

namespace ShareData
{
    public partial class MainPage: PhoneApplicationPage
    {
        // Constructor
        public MainPage ()
        {
            InitializeComponent ();
        }
        /// <summary>
        /// click to navigate to the second page
        /// </ summary>
        /// <param name = "sender"> </ param>
        /// <param name = "e"> </ param>
        private void btn_Click (object sender, RoutedEventArgs e)
        {
            this.NavigationService.Navigate (new Uri ("/ SecondPage.xaml", UriKind.Relative));
        }
       // Knowledge points①
        protected override void OnNavigatedFrom (System.Windows.Navigation.NavigationEventArgs e)
        {
            // Target page-knowledge point ②
            if (e.Content is SecondPage)
            {
                ((SecondPage) e.Content) .ApplicationTitle.Text = "Data passed successfully!";
            }
            // Get a reference to the application object-knowledge point ③
            (Application.Current as App) .shareData = "Share data through the properties of the APP class";
            // State management of the application --- knowledge points ④
            PhoneApplicationService.Current.State ["Share"] = "Temporary data";

            base.OnNavigatedFrom (e);
        }

        ///// <summary>
        ///// accept the passed value
        ///// </ summary>
        ///// <param name = "e"> </ param>
        // protected override void OnNavigatedTo (System.Windows.Navigation.NavigationEventArgs e)
        // {
        // // Get shared data in App class
        // PageTitle.Text = (Application.Current as App) .shareData.ToString ();
        // if (PhoneApplicationService.Current.State.ContainsKey ("Share"))
        // {
        // // Get the state property set in the phoneapplicationService object
        // PageTitle.Text + = "\ n" + PhoneApplicationService.Current.State ["Share"]. ToString ();
        //}
        // base.OnNavigatedTo (e);
        //}
    }
}

In the created secondpage. in the XAML file, I only added a button element, set the content to be displayed, and defined the touch event of the element: <button X: name = "BTN" content = "navigate to 1st pages" grid. row = "1" Click = "btn_click"> </button>

The hidden files of secondpage also need to reference the same namespace:

// Reference the namespace -- used by the phoneapplicationservice class
Using Microsoft. Phone. shell;

 

The code of the hidden secondpage file is as follows:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
// Reference namespace-used by PhoneApplicationService class
using Microsoft.Phone.Shell;

namespace ShareData
{
    public partial class SecondPage: PhoneApplicationPage
    {
        public SecondPage ()
        {
            InitializeComponent ();
        }
        /// <summary>
        /// accept the passed value
        /// </ summary>
        /// <param name = "e"> </ param>
        protected override void OnNavigatedTo (System.Windows.Navigation.NavigationEventArgs e)
        {
            // Get shared data in App class
            PageTitle.Text = (Application.Current as App) .shareData.ToString ();
            if (PhoneApplicationService.Current.State.ContainsKey ("Share"))
            {
                // Get the state property set in the phoneapplicationService object
                PageTitle.Text + = "\ n" + PhoneApplicationService.Current.State ["Share"]. ToString ();
            }
            base.OnNavigatedTo (e);
        }
        /// <summary>
        /// navigate to the first page
        /// </ summary>
        /// <param name = "sender"> </ param>
        /// <param name = "e"> </ param>
        private void btn_Click (object sender, RoutedEventArgs e)
        {
            this.NavigationService.GoBack ();;
        }


        // protected override void OnNavigatedFrom (System.Windows.Navigation.NavigationEventArgs e)
        // {
        // if (e.Content is SecondPage)
        // {
        // ((SecondPage) e.Content) .PageTitle.Text = "Data passed successfully!";
        //}
        // (Application.Current as App) .shareData = "Share data through the properties of the APP class";

        // PhoneApplicationService.Current.State ["Share"] = "Temporary data";

        // base.OnNavigatedFrom (e);
        //}

One of the three parameters is to share multiple pages by setting attributes under the app class, directly setting the public attributes in the app class:

// Set shared data
Public String collect data {Get; set ;}

So far, all the code has been presented here, so how do we share data? OK, details are as follows: First, click the button event in mainpage, because no other code needs to be executed, the onnavigatedfrom method on the mainpage will be executed immediately after the component is executed. We can see that the onnavigatedfrom parameter is system. windows. navigation. navigationeventargs is the parameter for navigation. After the onnavigatedfrom method is executed, it will navigate to the secondpage page. The hidden file of secondpage loads the constructor first, and then the onnavigatedto method.

The onnavigatedto method accepts transmitted data. In the same principle, we can pass the data in secondpage to mainpage. The commented out part of the code is to implement this content, mainpage hides the comments in the file. If you remove the comments, an error will be reported during running, because the onnavigatedfrom method will be executed after the program enters the mainpage page and triggers the button event, at this time, no content is transmitted;

 

 

Here, onnavigatedfrom is rewritten to be last executed when the page becomes inactive, so some operations can be completed on this page; as we can assign values here to the text attribute in the textblock element of the target page;

 

 

System. windows. navigation. the navigationeventargs parameter records some information when we click the navigation bar. E. content indicates the page we want to navigate to, such as (secondpage) E. content ). applicationtitle. TEXT = "data passed! "; We also access the attributes of the target.

 

 

The app class is used to share the parameter because all pages in the program can access the app class derived from the application, and the attributes set in the app class can also be accessed, the Static Property of the application class current returns a reference to the Application object. If you want to convert it to a derived app class, you can forcibly convert it.

 

The phoneapplicationservice class is instantiated in the app. XAML file.

<Application
     x: Class = "ShareData.App"
     xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation"
     xmlns: x = "http://schemas.microsoft.com/winfx/2006/xaml"
     xmlns: phone = "clr-namespace: Microsoft.Phone.Controls; assembly = Microsoft.Phone"
     xmlns: shell = "clr-namespace: Microsoft.Phone.Shell; assembly = Microsoft.Phone">

     <!-Application Resources->
     <Application.Resources>
     </Application.Resources>

     <Application.ApplicationLifetimeObjects>
         <!-Objects needed to handle application lifetime events->
         <shell: PhoneApplicationService
             Launching = "Application_Launching" Closing = "Application_Closing"
             Activated = "Application_Activated" Deactivated = "Application_Deactivated" />
     </Application.ApplicationLifetimeObjects>

</ Application> 
The phoneapplicationservice class provides temporary storage for data, which can be retained only during running (the Independent storage space can be retained permanently ), the state attribute of this class can be set to a dictionary container, but all objects stored in the state dictionary must be serializable. serializable means that objects can be converted to XML, XML can also be deserialized into objects.

 

 

Method for loading the last page: onnavigatedfrom method; obtain the target page of the navigation: E. Content and perform forced conversion; access the public attributes of the app class; and save and read phoneapplicationservice. State temporarily;
Source code download

Related Article

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.