当的NavigationService初始化?初始化、NavigationService

2023-09-03 06:02:29 作者:不疯狂不青春

我想从我的页面从向前导航赶上NavigationService.Navigating事件,以prevent用户。我有一个事件处理程序中定义正是如此:

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;
    }
}

...并工作正常。不过,我不能确定究竟在何处放置此code:

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

NavigationService.Navigating += PreventForwardNavigation;

如果我把它放在网页,或初始化事件处理程序的构造函数,那么的NavigationService仍然是空,我得到一个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事件把它挂)?如果没有,是否有在初始化和加载之间的一些地方,我可以做到这一点的布线?

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...
    }
}