問題描述
我想從我的頁面中捕獲 NavigationService.Navigating 事件,以防止用戶向前導(dǎo)航.我有一個(gè)這樣定義的事件處理程序:
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;
如果我將它放在頁面的構(gòu)造函數(shù)或 Initialized 事件處理程序中,則 NavigationService 仍然為 null,并且我得到 NullReferenceException.但是,如果我將它放在頁面的 Loaded 事件處理程序中,那么每次導(dǎo)航到頁面時(shí)都會(huì)調(diào)用它.如果我理解正確,這意味著我要多次處理同一個(gè)事件.
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 事件來連接它會(huì)發(fā)生這種情況)?如果沒有,在 Initialized 和 Loaded 之間是否有一些地方可以進(jìn)行這種接線?
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
觸發(fā) NavigationService.Navigating
事件和 Application.Navigating代碼>事件.我用以下方法解決了這個(gè)問題:
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...
}
}
這篇關(guān)于NavigationService 什么時(shí)候初始化?的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!