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

B. *_*non 1 c# visual-studio-2012 windows-store-apps

试图确定为什么我的应用程序(基于"空白应用程序"模板进入这个勇敢的新世界)不能像我期望的那样工作(http://stackoverflow.com/questions/14467756/why-would-my -event-handler-not-get-called),我启动了一个新的Blank项目,然后删除了MainPage并添加了一个新的Basic(非空白)页面,我将其命名为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)
        {
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

...我用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)
        {
        }
    }
Run Code Online (Sandbox Code Playgroud)

因此,基本页面获取LoadState()和SaveState(),而空白页面的MainPage具有OnNavigatedTo().为什么基本页面也没有OnNavigatedTo()事件?似乎每个页面都有可能被导航到(并且从那个事件我可以看到更可能是可选的/不必要的).

Dam*_*Arh 5

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

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

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

    // add you own code here
}
Run Code Online (Sandbox Code Playgroud)

只要确保你保持base.OnNavigatedTo(e)通话,否则你将失去已经实现的功能LayoutAwarePage(启用LoadState/ SaveState).

如果您不知道,在Visual Studio中为您的类添加覆盖非常容易.只需键入override并按空格键,系统就会打开一个下拉列表,其中包含您可以在班级中覆盖的所有方法.一旦你选择其中一个,完整的空方法将被添加到你的班级,就像我在上面的答案中包含的那个.