如您所见,我想导航到“ ScoreInputDialog.xaml”页面,用户可以在其中输入名称。此后,我尝试将名称保存到列表中,但它始终为空,因为最后完成了对页面“ ScoreInputDialog.xaml”的导航。在继续其余代码之前,如何导航到所需页面并获得价值?

NavigationService.Navigate(new Uri("/ScoreInputDialog.xaml", UriKind.Relative)); // Sets tempPlayerName through a textbox.
if (phoneAppService.State.ContainsKey("tmpPlayerName"))
{
    object pName;
    if (phoneAppService.State.TryGetValue("tmpPlayerName", out pName))
    {
        tempPlayerName = (string)pName;
    }
}
highScorePlayerList.Add(tempPlayerName);

最佳答案

Navigate调用之后,您不应直接执行任何操作。而是重写您来自的页面的OnNavigatedTo方法,以在用户回来时得到通知:

protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)


当用户退出“ ScoreInputDialog.xaml”时,可能会通过按“后退”按钮或因为您调用NavigationService.GoBack()来调用此方法。这将退出“ ScoreInputDialog.xaml”页面,并转到上一页,将在其中调用OnNavigatedTo。现在该检查该值了。

导航流程的图示:

“ OriginPage” --- [Navigate] --->“ ScoreInputDialog” --- [GoBack()或Back-button] --->“ OriginPage”(*)

哪里有(*),将调用OnNavigatedTo。该实现可能如下所示:

protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
{
    if (phoneAppService.State.ContainsKey("tmpPlayerName"))
    {
        object pName;
        if (phoneAppService.State.TryGetValue("tmpPlayerName", out pName))
        {
            tempPlayerName = (string)pName;
        }
        highScorePlayerList.Add(tempPlayerName);
    }
}


在调用Navigate之前,请记住清除临时播放器的名称:

phoneAppService.State.Remove("tmpPlayerName");
NavigationService.Navigate(new Uri("/ScoreInputDialog.xaml", UriKind.Relative));


注意:当用户第一次看到该页面或从“ ScoreInputDialog.xaml”以外的其他页面导航时,也会调用OnNavigatedTo。但是,则不会设置“ tmpPlayerName”值。

关于c# - 为什么NavigationService.Navigate仅在最后运行?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/8234333/

10-09 06:43