Search code examples
c#wpfnavigationservice

What determines whether NavigationCommands.BrowseBack calls the page constructor?


I have two pages with similar logic in them. Load the page, click some buttons that will show/hide other buttons, continue to next page. When I hit the next page, if I click the back button I am returned to the previous page.

The difference is that one page (FirstPage) will have the constructor called when I click the back button, which has a call to reset the defaults. The other page (SecondPage) doesn't get the constructor called and I'm not sure why.

public FirstPage()
{
  InitializeComponent();
  DisplayStuff();
}

FirstPage has KeepAlive set to False.

public SecondPage(object arg1, object arg2)
{
  InitializeComponent();
  DisplayStuff(arg1, arg2);
}

This page also has KeepAlive set to False. These two pages don't inherit from anything and there is nothing that overrides any of the properties. The only difference I can see is the empty constructor, so I tried giving SecondPage an empty constructor and still no luck.

I'm relatively new to WPF (I work on it for an hour or two every 6 months), so what am I missing?

Here is the back button in case it is relevant.

<Button Command="{x:Static NavigationCommands.BrowseBack}" />

Edit: When I click the back button, SecondPage doesn't keep its state. It just loads an empty page because DisplayStuff hasn't been called yet.

Navigation Code:

NavigateTo(new SecondPage(arg1, arg2));

protected void NavigateTo(Page page)
{
  NavigationService.Navigate(page);
}

Solution

  • I created a similar sample application and had similar behaviour. What I figured out that when you go back to a page the constructor is not called unless the page is the first page in the journal

    Read this section in Navigation in WPF:

    When the page Page is navigated back to, using the journal, the following steps take place:

    1. The Page (the top journal entry on the back stack) is instantiated.

    2. The Page is refreshed with the state that was stored with the journal entry for the Page.

    3. The Page is navigated back to.

    Good luck!