gpt4 book ai didi

c# - 为什么基本页面不提供 OnNavigatedTo() 事件?

转载 作者:太空宇宙 更新时间:2023-11-03 20:19:30 24 4
gpt4 key购买 nike

在尝试确定为什么我的应用程序(基于“空白应用程序”模板进入这个美丽的新世界)没有像我预期的那样工作(http://stackoverflow.com/questions/14467756/why- would-my-event-handler-not-get-called),我开始了一个新的空白项目,然后删除了 MainPage 并添加了一个新的基本(不是空白)页面,我将其命名为 MainPage 以纪念已故的页面(并且作为向传统和懒惰致敬 - 所以我不必更改导航到该页面的 app.xaml.cs 中的代码)。

Blank 应用程序像这样创建了原始的 MainPage.xaml.cs(自动生成的注释已省略):

namespace AsYouWish
{
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
}

protected override void OnNavigatedTo(NavigationEventArgs e)
{
}
}
}

...我用 BasicPage(不是 BlankPage)替换了它,它生成了这个:

namespace AsYouWish
{
public sealed partial class MainPage : AsYouWish.Common.LayoutAwarePage
{
public MainPage()
{
this.InitializeComponent();
}

protected override void LoadState(Object navigationParameter, Dictionary<String, Object> pageState)
{
}

protected override void SaveState(Dictionary<String, Object> pageState)
{
}
}

所以基本页面获得了 LoadState() 和 SaveState(),而空白页面的 MainPage 获得了 OnNavigatedTo()。为什么基本页面没有 OnNavigatedTo() 事件?似乎每个页面都有可能被导航到(和从中导航,但我认为该事件更有可能是可选的/不必要的)。

最佳答案

这只是所使用的页面模板的问题。 OnNavigatedTo 虚方法在 Page 类中实现,因此它可以在直接或间接继承自它的任何类中被覆盖。唯一的区别是用于 MainPage.xaml.cs 的模板已经有一个空的 OnNavigatedTo 方法,而 BasicPage 模板没有.

没有什么可以阻止您通过添加以下代码来覆盖该方法:

protected override void OnNavigatedTo(NavigationEventArgs e)
{
base.OnNavigatedTo(e);

// add you own code here
}

只需确保保留 base.OnNavigatedTo(e) 调用,否则您将失去已在 LayoutAwarePage 中实现的功能(启用 LoadState/SaveState).

如果您不知道,在 Visual Studio 中向您的类添加重写真的很容易。只需键入 override 并按空格键,就会打开一个下拉列表,其中包含您可以在类中覆盖的所有方法。选择其中之一后,完整的空方法将添加到您的类中,就像我在上面的答案中包含的方法一样。

关于c# - 为什么基本页面不提供 OnNavigatedTo() 事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14493001/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com