【问题标题】:How to determine what page you've just come from within OnNavigatedTo function?如何确定您刚刚来自 OnNavigatedTo 函数中的哪个页面?
【发布时间】:2017-08-09 04:44:00
【问题描述】:

我正在用 C# 创建一个 UWP 应用。我正在尝试在 OnNavigatedTo 函数中运行不同的代码块,具体取决于将我发送到那里的页面。现在我有 if else 语句来确定运行哪些代码块,具体取决于哪个页面将我发送到我现在所在的页面。

我现有的代码如下所示:

protected override void OnNavigatedTo(NavigationEventArgs e)
    //runs every time MainPage is Navigated to from another page or when program is first started and MainPage loads
    {
        if ([SomeAttribute == Page2])
         {
             //attempt to add string from page[2] to List
             if (e.Parameter is string && !string.IsNullOrWhiteSpace((string)e.Parameter) && !InspectorInst.Names_list.Contains(e.Parameter))
             //if thing passed from previous page (e.Parameter) is a string and isnt null or whitespace and isnt already in the Names_list
             {
                 string s = e.Parameter.ToString();//create string to hold e.Parameter
                 this.InspectorInst.Names_list.Add(s);//Add string to Names_list
             }
         }
        else{ 
             //do something else
         }
         base.OnNavigatedTo(e);
    }

[SomeAttribute == Page2] 如果将我引导到我当前所在页面的页面是 Page2,则应该返回 true。 SomeAttribute 会返回将我发送到我当前所在页面的页面。我无法在 UWP 文档中找到任何可以实现此目的的内容。

如果我以错误的方式解决这个问题,并且有更简单的方法来解决这个问题,那会是什么?

谢谢

【问题讨论】:

  • 您是否尝试过将页面名称作为参数传递?例如,您可以创建一个自定义对象,其中包含您的页面名称以及要发送的数据,然后在您的主页中,您可以检查页面名称并相应地处理数据..

标签: c# uwp uwp-xaml


【解决方案1】:

我认为,如果您希望页面根据调用位置具有不同的行为,通常的方法是将不同的值作为第二个参数传递给 Navigate 方法。

如果您绝对想知道调用了哪个页面,那么您可以检查导航堆栈中的最后一个条目,如下所示:

var entry = this.Frame.BackStack.LastOrDefault();
if (entry != null)
// Check entry.SourcePageType - it contains the type of the previous page 

请注意,您可能还必须检查 NavigationEventArgs.NavigationMode 以查看用户是否从页面返回。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-01
    • 2019-08-10
    • 2021-01-12
    • 2015-05-16
    • 1970-01-01
    相关资源
    最近更新 更多