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 什么时候初始化?
基础教程推荐
- 更新 Visual Studio 中的 DataSet 结构以匹配新的 SQL 数据库结构 2022-01-01
- 获取C#保存对话框的文件路径 2022-01-01
- C# 9 新特性——record的相关总结 2023-04-03
- 重新排序 WPF TabControl 中的选项卡 2022-01-01
- 在 VB6 或经典 ASP 中使用 .NET 2022-01-01
- Mono https webrequest 失败并显示“身份验证或解密失败" 2022-01-01
- 如果条件可以为空 2022-01-01
- 从 C# 控制相机设备 2022-01-01
- SonarQube C# 分析失败“不是指针的有效行偏移" 2022-01-01
- 将数据集转换为列表 2022-01-01
