Sunday, November 21, 2010

Different Ways to Pass Data Between Pages in WP7

I am new to the Silverlight world. I’ve primarily programmed client Windows Forms .NET applications. And I’ve never patterned any applications around MVVM. Therefore, WP7 has challenged me with new coding patterns that may seem trivial to ASP.NET or Silverlight/WPF programmers.

Just today I wanted to pass an object from one Page to another on my phone. I’m not really sure what the best/correct way is to do this. In the past I would use a Public Property or a Constructor parameter. I’m not sure how to do either of these in WP7. But, I did find some options.

  1. Global Static Object
  2. Parameter Passing on Navigation calls
  3. Isolated Storage

Global Static Object

The concept is that you have an object that is a static singleton class. You can set any values/objects you want in here and they will be accessible across your application.

While I was researching this solution, I realized this is a solution also suggested by Charles Petzold in his free WP7 programming eBook.


Parameter Passing

This option is useful if the data you are passing are simple datatypes like integers or strings. The calling page adds the data in the Navigate call:

NavigationService
.Navigate(new Uri("/Countdown.xaml?Start=10",
UriKind.RelativeOrAbsolute));

Then in your receiving page, you need read that data from the QueryString collection, just like you do in ASP.NET:

protected override void OnNavigatedTo
(System.Windows.Navigation.NavigationEventArgs e)
{
base.OnNavigatedTo(e);
_iStart = Convert
.ToInt32(NavigationContext.QueryString["Start"]);
}

Isolated Storage

This concept involves:

  • serializing your objects
  • saving it to a file in isolated storage
  • loading that file from your other page
  • deserializing that object

Given those options, it’s arguable that not one way is the best. I already have an idea where each option would work out best.

The global variable will be structures of data that I may want to pass data back-and-forth in.

QueryString will work great when I just need to reference a single item in the new page, and data doesn’t have to be sent back.

Isolated Storage will work out well when I have data that may get used in a number of locations, and across instances of the application. This data can also be loaded into a global variable.

No comments:

Post a Comment