How to pass Data between Pages in Windows Phone 7

There are several methods that you can use to pass Data between pages.

1) The one I prefer is to store the values entered on PageTwo in a object Model that is also accessible to PageOne, possibly part of the DataSource of one of the pages.

2) An other methods is to use a Global Variable defined in the App.xaml file

public string PageTwoText { get; set; }

On your PageTwo you can add a value to that variable:

(App.Current as App).PageTwoText = txtBox.Text;

and in the PageOne get it:

protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e) {
     base.OnNavigatedTo(e);
     txtBlock.Text = (App.Current as App).PageTwoText;
}

3) An other method is to use a Query String: this procedure is good when we just need to share string based data between two pages. In PageOneyou cna navigate to PageTwo in this way:

NavigationService.Navigate(new Uri("/PageTwo.xaml?Text=" + txtBox.Text + "&Number=" + oneNumber, UriKind.Relative));

and in PageTwo get them:

protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e) {
	 base.OnNavigatedTo(e);
         IDictionary<string, string> parameters = this.NavigationContext.QueryString;
         if (parameters.ContainsKey("Text")){
             txtBlock.Text = parameters["Text"];
         }
         //this is an other way to get a parameter
         string monthParam;
         if (NavigationContext.QueryString.TryGetValue("Number", out monthParam)) {
                 this.selectorDay.DataSource.SelectedItem = Convert.ToInt32(monthParam);
         }
}

4) Onother way is to use the PhoneApplicationService States: each application has one PhoneApplicationService defined in its App.xaml file. We can use this service’s property called “State”. These “States” are all transient data which means they are available only for one instant of your application which means once you restart your application these states will be lost. Also we should not try to create a new PhoneApplicationService instead we must try to use the service from the current instant.
In PageOne you can set a state:

protected override void OnNavigatedFrom(System.Windows.Navigation.NavigationEventArgs e) {
    base.OnNavigatedTo(e);
    PhoneApplicationService.Current.State["Text"] = txtBox.Text;
}

and in PageTwo you can get it:

protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e) {
    base.OnNavigatedTo(e);
    if(PhoneApplicationService.Current.State.ContainsKey("Text"))
        txtBlock.Text = (string)PhoneApplicationService.Current.State["Text"];
}

You can also use of the following utility class to semplify the usage of the PhoneApplicationService.Current.State. Note that the Get method has two optional parameters: the first allows to remove or not the key after being read, the other gives the default value if that key is not found.

/// <summary>
/// Wraps calls to the Microsoft.Phone.Shell.PhoneApplicationService helper class, which handles the phone’s transient state, with generic get/set methods.
/// </summary>
public static class TransientState {

        public static void Set<T>(string key, T state) {
            PhoneApplicationService.Current.State[key] = state;
        }

        public static T Get<T>(string key, bool remove = true, T defaultValue = default(T)) {
            object state;
            if (!PhoneApplicationService.Current.State.TryGetValue(key, out state)) {
                state = defaultValue;
            } else {
                if (remove) {
                    PhoneApplicationService.Current.State.Remove(key);
                }
            }
            return (T)state;
        }
}

5) Last method is to use NextPage instance: whenever we “Navigate” from a PageOne to a “/PageTwo.xaml”, the OnNavigatedFrom method in current page is called with event arguments with a Uri property indicating the next page and with a Content property of the type of that Navigating page. We have here the opportunity to set the value of some variables of the next page, prior to navigate to it. So, in the following example that shows the OnNavigatedFrom method of PageOne, you can already set the variable txtBlock.Text of PageTwo that, after navigation, it will need to do nothing and just use that variable already set by PageOne:

protected override void OnNavigatedFrom(System.Windows.Navigation.NavigationEventArgs e) { //method of PageOne
    base.OnNavigatedTo(e);
    if (e.Content is PageTwo) {
        (e.Content as PageTwo).txtBlock.Text = txtBox.Text;
    }
}
Annunci

Informazioni su Enzo Contini

Electronic engineer
Questa voce è stata pubblicata in Windows Phone/Mobile e contrassegnata con . Contrassegna il permalink.

4 risposte a How to pass Data between Pages in Windows Phone 7

  1. Pingback: Windows Phone. Navegación. Paso de objetos. | Javier Suárez Ruiz | Blog

  2. muhammad koxi ha detto:

    great job dude you helped me alot

    • Enzo Contini ha detto:

      Not at all, Muhammad!
      You are the first to post a comment in the programming category of this blog and I am very glad to you: thank you for your appreciation!
      Everytime, when I program, I’ll learn something that I suppose it can be useful to someone, as soon as I have time, I’ll post in this blog.
      Let you be tuned if you like and … happy coding!!! 😉

Lascia un Commento/Leave a comment

Inserisci i tuoi dati qui sotto o clicca su un'icona per effettuare l'accesso:

Logo WordPress.com

Stai commentando usando il tuo account WordPress.com. Chiudi sessione / Modifica )

Foto Twitter

Stai commentando usando il tuo account Twitter. Chiudi sessione / Modifica )

Foto di Facebook

Stai commentando usando il tuo account Facebook. Chiudi sessione / Modifica )

Google+ photo

Stai commentando usando il tuo account Google+. Chiudi sessione / Modifica )

Connessione a %s...