在Android应用中,我们使用Intent在不同页面之间进行导航,那么在Windows Mobile中,其对应物是什么呢?答案就是:
NavigationService
关于其类型定义及属性方法等,请参考
MSDN站点。
在不同页面间导航,就不可避免的遇到需要传递参数的情形。在Android应用中,我们可以方便的使用intent.putExtras来实现,在WP中则不行。下面介绍一下在WP中的传参方式。
1. 对于简单的参数,可以直接将参数附在导航目标后,作为查询参数。
例如:
NavigationService.Navigate(new Uri("SecondPage.xaml?param1=1¶m2=true", UriKind.Relative));
在目标页面中,OnNavigateTo()方法中可以通过如下方式来读取参数:
NavigationContext.QueryString.TryGetValue( "category", out category);
NavigationContext.QueryString.TryGetValue(
"title"
,
out
title);
2. 利用PhoneApplicationService
PhoneApplicationService有一个State属性,它是Dictionary类型的,允许你存取任意值。
但也有其限制,放进State里的对象必须是可序列化的。
PhoneApplicationService.Current.State["Color"] = clr;
3. 利用App类来共享数据
应用中的所有页面都可以方便的访问Application的子类App。这样我们就可以利用Application.Current来获取App的实例,然后用它来共享不同页面间需要的数据。
譬如,我们可以在App类中添加一个属性:
public partial class App : Application
{
// public property for sharing data among pages
public SharedParameter SharedParam { set; get; }
…
}
当需要传递数据时,在第一个页面的onNavigateFrom()方法里,将需要传递的参数赋给App的相应属性,在接下来的页面实例中就可以访问了。
4. 在起始页面的OnNavigatedFrom方法中设置目标页面的属性。
在目标页面中定义需要传递的属性:
public ChannelItem selectedChannel { get; set; }
在其实页面中通过设置NavigationEventArgs参数的Content属性来进行传递:
protected override void OnNavigatedFrom(NavigationEventArgs args)
{
if (contentListBox.SelectedItem != null)
{
if (contentListBox.SelectedItem is ChannelItem)
{
ChannelItem selectedItem = (ChannelItem)contentListBox.SelectedItem;
if (args.Content is RSSChannelPage)
{
(args.Content as RSSChannelPage).selectedChannel = selectedItem;
}
}
}
}
以上方法均参考自《Programming Windows Phone7》 Chapter 6.