我正在开发一个Windows Phone应用程序,这是我遇到问题的场景:
所以我有三页,我们称之为第1,2,3页。
在第1页中,我有一个名为start downloading
的按钮。单击按钮并使用NavigateService.Navigate(page2Uri)
并导航到第2页。
第2页从互联网查询和下载图像,因此在其OnNavigateTo
处理程序中,我检查页面堆栈,如果从第1页导航,我将进行下载。在此页面的应用栏中,我有一个可以导航到第3页的按钮。
第3页是一个选项列表,它将对第2页中下载的图像执行某些操作。一旦我选择了一个选项,我想回到第2页并对加载的图像执行一些操作。
问题来了:
如果我使用NavigateService.Navigate(page2Uri)
从第3页导航到第2页,它将再次调用Page2构造函数和OnNavigateTo
处理程序,这将导致它丢失已经获得的每个实例变量。
但是,如果我使用NavigatService.GoBack
,它将返回第2页,然后意识到backstack top条目是page1(因为page1 - > page2 - > page3)。所以它会再次重新下载所有内容。
从第3页导航到第2页时,我不希望再次下载任何内容。所以想知道是否有人对此有好感。
谢谢。
答案 0 :(得分:5)
您可以使用查询参数和NavigationEventArgs来帮助。
首先,您可以使用NavigationEventArgs通过检查NavigationMode来确定用户是前进还是后台。
其次,您可以使用查询参数告诉第2页下载。
从第1页开始:
private void MoveToPage2FromPage1()
{
NavigationService.Navigate(new Uri("/Page2.xaml?shouldDownload=true", UriKind.Relative));
}
和第2页:
protected override void OnNavigatedTo(NavigationEventArgs e)
{
if (e.NavigationMode == NavigationMode.Back) return;
string shouldDownload = ""; //May not be needed if you'll only ever go to page 2 from page 1 to download...
if (NavigationContext.QueryString.TryGetValue("shouldDownload", out shouldDownload))
{
Convert.ToBoolean(shouldDownload);
}
}
答案 1 :(得分:2)
有几种方法可以将数据传递到另一个页面:
这完全取决于具体情况。我认为Shawns建议使用查询参数可能是最“正确”的MVVM方式,但其他方法都有它们的位置。
答案 2 :(得分:0)
您需要实现以下功能和导航服务。 这些代码肯定会解决您的问题
对于两个或更多参数,请使用此代码
String download="true";
String file="image";
NavigationService.Navigate(new Uri("/Page3.xaml?download="+download+"&file="+file+"", UriKind.Relative));
OnNavigatedTo,将以下代码添加到您的Page2
protected override void OnNavigatedTo(NavigationEventArgs e)
{
base.OnNavigatedTo(e);
String download=NavigationContext.QueryString["download"];
String file=NavigationContext.QueryString["file"];
}
对于上面的OnNavigatedTo函数输出true和image。您可以使用MessageBox.Show();
输出