Original solution : Non-string parameters between pages in Windows Phone

My last post was about an original solution using Dependency properties. This time another original solution passing non-string parameters between pages in Windows Phone.

In WPF or Windows Runtime (aka Windows Store apps) you can pass parameters between pages as objects and this means that you don’t have any problem to pass parameters. But, in Windows Phone only parameters as string is possible. For example:


NavigationService.Navigate(new Uri("yourpage.xaml?parameter1=value1&parameter2=value2,UriKind.Absolute));

As you can see, navigate in Windows Phone is like web pages. Only using Uri you can pass parameters, and this parameters need to be in string format.

Yes, this is a problem, because in some cases, we are using complex objects structures in a page and we would like to pass this same complex structure to another page.

A solution is to serialize the object with DataContract attribute. But, the problem is, no all object can be serialized and the Uri is length limited.

An original solution that I found on internet is using an extension for NavigationService and a static field to save the object to pass to another page. Look an example:


public static class NavigationExtensions {

private static object _navigationData = null;

public static void Navigate(this NavigationService service, string page, object data)

{

_navigationData = data;

service.Navigate(new Uri(page, UriKind.Relative));

}

public static object GetLastNavigationData(this NavigationService service)

{

object data = _navigationData;

_navigationData = null;

return data;

}

}

Simply clever, awesome.

Then, you can call on the source page


NavigationService.Navigate("mypage.xaml", myParameter);

And on the target page in the OnNavigatedTo


var myParameter = NavigationService.GetLastNavigationData();

Source:

How do I pass non-string parameters between pages in windows phone 8?