When is NavigationService initialized?

后端 未结 2 1533
死守一世寂寞
死守一世寂寞 2021-01-21 08:32

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 Pr         


        
相关标签:
2条回答
  • 2021-01-21 08:54

    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...
        }
    }
    
    0 讨论(0)
  • 2021-01-21 08:59

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

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

    So you basically have to unsubscribe from the navigation service's events when your page is unloaded.

    +1 to your response for helping me find it. I don't seem to be able to mark my own response as the "accepted answer" so I guess I'll leave it for now.

    0 讨论(0)
提交回复
热议问题