There’s multiple ways to pass data between pages in Windows Phone apps. Most frequently used ways include:
- Query strings
- Application state
- Static properties in App.xaml.cs
One alternative, which I haven’t seen discussed that much, is Application.Resources. Using Application.Resources has these benefits:
- You can store almost anything in there, including complex objects (List<Customer> etc.)
- Application.Resources can be accessed from anywhere. You can split the app into multiple assemblies and all these can access Application.Resources.
- It’s easy to use
The simple “pattern” for using Application.Resources to pass data between pages looks like this:
- Call Application.Current.Resources.Add (mydata, “mykey”) to add the data
- Navigate to an another page
- Call Application.Current.Resources[“mykey”] to retrieve the data
Store the data before navigation:
var customers = GetCustomers(); Application.Current.Resources.Add("NavigationParam", customers); NavigationService.Navigate(new Uri("/Page2.xaml", UriKind.Relative));
Retrieve the data after navigation:
var customers = (List<Customer>) Application.Current.Resources["NavigationParam"];
This process can be made even easier with a simple helper. With it, you could write the following code to store the data:
var customers = GetCustomers(); ParameterHelper.Store(customers);
And the following code to retrieve it:
var customers = ParameterHelper.Get<List<Customer>>();
- The data is lost if the application is tombstoned.
- If there already exists data in Application.Resources with key “NavigationParam” and you try to add new data with the same key, an exception is thrown. Always remember to remove the existing data.
An example project (which includes the ParameterHelper) is available from GitHub (folder windows-phone-application-resources-navigation).