0

我对“重新初始化”MainWindow 对象设置有疑问。我认为 OnNavigatedTo 也会在暂停后调用,我在 MainWindow 中有一些代码,例如:protected override void OnNavigatedTo(NavigationEventArgs e) { object.value = initValue; }

但是在暂停后它没有被调用。那么暂停后怎么办呢?

4

1 回答 1

1

如果您使用 VS2012 附带的默认模板,您将在 App.xaml.cs 文件中看到以下代码:

    protected override async void OnLaunched(LaunchActivatedEventArgs args)
    {
        Frame rootFrame = Window.Current.Content as Frame;

        // ... took out some code here

            if (args.PreviousExecutionState == ApplicationExecutionState.Terminated)
            {
                // Restore the saved session state only when appropriate
                try
                {
                    await SuspensionManager.RestoreAsync();
                }
                catch (SuspensionManagerException)
                {
                    //Something went wrong restoring state.
                    //Assume there is no state and continue
                }
            }

        // ... took out some more code here    

        Window.Current.Activate();
    }

ApplicationExecutionState 的可能值为

public enum ApplicationExecutionState
{
    // Summary:
    //     The app is not running.
    NotRunning = 0,
    //
    // Summary:
    //     The app is running.
    Running = 1,
    //
    // Summary:
    //     The app is suspended.
    Suspended = 2,
    //
    // Summary:
    //     The app was terminated after being suspended.
    Terminated = 3,
    //
    // Summary:
    //     The app was closed by the user.
    ClosedByUser = 4,
}

所以只需添加另一个 if 语句

if (args.PreviousExecutionState == ApplicationExecutionState.Suspended)

在挂起状态后执行要执行的代码。

要恢复页面本身的先前状态,请使用在每个页面的 LayoutAwarePage 基类上定义的 LoadState 和 SaveState 方法(或实现您自己的状态管理)。VS2012 附带的模板(例如 Grid 应用程序)已经使用了所有这些技巧来进行状态管理,并且是入门的好方法。

protected override void LoadState(Object navigationParameter, Dictionary<String, Object> pageState)
protected override void SaveState(Dictionary<String, Object> pageState)
于 2012-08-17T08:36:18.657 回答