NavigationService 什么时候初始化? [英] When is NavigationService initialized?

查看:24
本文介绍了NavigationService 什么时候初始化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从我的页面中捕获 NavigationService.Navigating 事件,以防止用户向前导航.我有一个这样定义的事件处理程序:

I want to catch the NavigationService.Navigating event from my Page, to prevent the user from navigating forward. I have an event handler defined thusly:

void PreventForwardNavigation(object sender, NavigatingCancelEventArgs e)
{
    if (e.NavigationMode == NavigationMode.Forward)
    {
        e.Cancel = true;
    }
}

... 效果很好.但是,我不确定该代码的确切位置:

... and that works fine. However, I am unsure exactly where to place this code:

NavigationService.Navigating += PreventForwardNavigation;

如果我将它放在页面的构造函数或 Initialized 事件处理程序中,则 NavigationService 仍然为 null,并且我得到 NullReferenceException.但是,如果我将它放在页面的 Loaded 事件处理程序中,那么每次导航到页面时都会调用它.如果我理解正确,这意味着我要多次处理同一个事件.

If I place it in the constructor of the page, or the Initialized event handler, then NavigationService is still null and I get a NullReferenceException. However, if I place it in the Loaded event handler for the Page, then it is called every time the page is navigated to. If I understand right, that means I'm handling the same event multiple times.

我可以多次向事件添加相同的处理程序吗(如果我使用页面的 Loaded 事件来连接它会发生这种情况)?如果没有,在 Initialized 和 Loaded 之间是否有一些地方可以进行这种接线?

Am I ok to add the same handler to the event multiple times (as would happen were I to use the page's Loaded event to hook it up)? If not, is there some place in between Initialized and Loaded where I can do this wiring?

推荐答案

NavigationService.Navigate 触发 NavigationService.Navigating 事件和 Application.Navigating事件.我用以下方法解决了这个问题:

NavigationService.Navigate triggers both a NavigationService.Navigating event AND an Application.Navigating event. I solved this problem with the following:

public class PageBase : Page
{
    static PageBase()
    {
        Application.Current.Navigating += NavigationService_Navigating;
    }

    protected static void NavigationService_Navigating(object sender, NavigatingCancelEventArgs e)
    {
        // put your event handler code here...
    }
}

这篇关于NavigationService 什么时候初始化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆