开发者

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开发者_StackOverflow 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);
}


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!


After reading Paul Stovell's article on WPF navigation, the way I want to display stuff is not going to work.

When navigating, if you click "Back", WPF can't possibly know what values to pass to the constructor; therefore it must keep the page alive. Here's the trace output:

Since WPF can't call the constructor, it won't. It'll just keep the page alive.

He goes on to mention that KeepAlive doesn't work if you're not navigating via URI, and Loaded and Unloaded are called each time, so I can just move all my logic there and I won't need the constructor to be called on the back navigation.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜