Why does the Basic Page not supply an OnNavigatedTo() event?

In trying to determine why my app (which came into this brave new world based on thte "Blank App" template) isn't working like I would expect (http://stackoverflow.com/questions/14467756/why-would-my-event-handler-not-get-called), I started a new Blank project, and then deleted MainPage and added a new Basic (not Blank) page which I named MainPage in honor of the dearly departed page (and as a nod to tradition and laziness - so I wouldn't have to change the code in app.xaml.cs which navigates to that page).

The Blank app created the original MainPage.xaml.cs like this (auto-generated comment elided):

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

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

...I replaced it with a BasicPage (not BlankPage), and it generated this:

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)
        {
        }
    }

So the Basic Page gets LoadState() and SaveState(), whereas the Blank Page's MainPage had OnNavigatedTo(). Why does the Basic Page not also have an OnNavigatedTo() event? It seems as if every page has the possibility of being navigated to (and from, but that event I can see as more likely being optional/unnecessary).

Upvotes: 1

Views: 4551

Answers (1)

Damir Arh
Damir Arh

Reputation: 17855

This is just a matter of the page template that is being used. OnNavigatedTo virtual method is implemented in Page class therefore it can be overriden in any class inherited directly or indirectly from it. The only difference is that the template used for MainPage.xaml.cs already has an empty OnNavigatedTo method in it and the BasicPage template doesn't.

There's nothing stopping you from overriding the method by adding the following code:

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

    // add you own code here
}

Just make sure you keep the base.OnNavigatedTo(e) call or you'll lose the functionality that's already implemented in LayoutAwarePage (enabling LoadState/SaveState).

In case you don't know, it's really easy to add overrides to your class in Visual Studio. Just type override and press space and a dropdown will open with all the methods that you can override in your class. Once you select one of them the complete empty method will be added to your class, just like the one I've included in my answer above.

Upvotes: 5

Related Questions