What determines whether NavigationCommands.BrowseBack calls the page constructor?

痞子三分冷 提交于 2019-12-14 03:51:18

问题


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

回答1:


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!




回答2:


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.



来源:https://stackoverflow.com/questions/5641248/what-determines-whether-navigationcommands-browseback-calls-the-page-constructor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!