When is the NavigationService function initialized?

I want to catch the NavigationService.Navigating event from my page so that the user cannot move forward. I defined an event handler:

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

... and it works great. However, I don’t know exactly where to place this code:

NavigationService.Navigating += PreventForwardNavigation;

If I put it in a page constructor or an initialized event handler, then the NavigationService is still null, and I get a NullReferenceException. However, if I put it in the Loaded event handler for the page, then it is called every time the page moves. If I understand correctly, this means that I process the same event several times.

Is it possible to add the same handler to the event several times (as it would be if I used the Loaded event page to link it)? If not, is there a place between initialization and loading, where can I post this?

+3
source share
2 answers

@Espo your link helped me find a workaround. I call this a workaround because it is ugly, but this is what MS themselves do in their documentation:

public MyPage() // ctor
{
    InitializeComponent();
    this.Loaded += delegate { NavigationService.Navigating += MyNavHandler; };
    this.Unloaded += delegate { NavigationService.Navigating -= MyNavHandler; };
}

Therefore, you basically should unsubscribe from navigation service events when your page is unloaded.

+1 to your answer to help me find it. It seems that I cannot mark my own answer as an “accepted answer”, so I think I’ll leave it now.

+1
source

NavigationService.Navigate a NavigationService.Navigating Application.Navigating. :

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

Source: https://habr.com/ru/post/1696523/


All Articles