NavigationService 什么时候初始化?

When is NavigationService initialized?(NavigationService 什么时候初始化?)
本文介绍了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 什么时候初始化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
quot;Overflowquot; compiler error with -9223372036854775808L(编译器错误-9223372036854775808L(Q;溢出Q))
Visual Studio 2010 ReportViewer Assembly References(Visual Studio 2010 ReportViewer程序集引用)
Weird behaviour when I open a reportviewer in WPF(在WPF中打开报表查看器时出现奇怪的行为)
how do i pass parameters to aspnet reportviewer(如何将参数传递给aspnet report查看器)