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


- 良好实践:如何重用 .csproj 和 .sln 文件来为 CI 创建 2022-01-01
- 在哪里可以找到使用中的C#/XML文档注释的好例子? 2022-01-01
- MoreLinq maxBy vs LINQ max + where 2022-01-01
- WebMatrix WebSecurity PasswordSalt 2022-01-01
- 输入按键事件处理程序 2022-01-01
- C#MongoDB使用Builders查找派生对象 2022-09-04
- Web Api 中的 Swagger .netcore 3.1,使用 swagger UI 设置日期时间格式 2022-01-01
- 带有服务/守护程序应用程序的 Microsoft Graph CSharp SDK 和 OneDrive for Business - 配额方面返回 null 2022-01-01
- C# 中多线程网络服务器的模式 2022-01-01
- 如何用自己压缩一个 IEnumerable 2022-01-01