在创建Windows 8应用程序时保存页面之间的状态

Ric*_*nks 4 c# windows-store-apps

我一直在使用Microsoft提供的C#或Visual Basic教程创建您的第一个Windows应用商店应用程序,但在页面之间导航时遇到一些保存状态的问题.

使用C#或Visual Basic创建您的第一个Windows应用商店应用

第3部分:导航,布局和视图

基本上我已经注意到,如果我从主页面导航到照片页面选择一张照片,导航回主页面,然后再次转到照片页面,它不记得所选的照片.我正在使用以下代码从主页面导航到照片页面.

private void photoPageButton_Click(object sender, RoutedEventArgs e)
{
    this.Frame.Navigate(typeof(PhotoPage));
}
Run Code Online (Sandbox Code Playgroud)

在照片页面中,loadstate方法是

protected async override void LoadState(Object navigationParameter, Dictionary<String, Object> pageState)
{
    if (pageState != null && pageState.ContainsKey("mruToken"))
    {
        object value = null;
        if (pageState.TryGetValue("mruToken", out value))
        {
            if (value != null)
            {
                mruToken = value.ToString();

                // Open the file via the token that you stored when adding this file into the MRU list.
                Windows.Storage.StorageFile file =
                    await Windows.Storage.AccessCache.StorageApplicationPermissions.MostRecentlyUsedList.GetFileAsync(mruToken);

                if (file != null)
                {
                    // Open a stream for the selected file.
                    Windows.Storage.Streams.IRandomAccessStream fileStream =
                        await file.OpenAsync(Windows.Storage.FileAccessMode.Read);

                    // Set the image source to a bitmap.
                    Windows.UI.Xaml.Media.Imaging.BitmapImage bitmapImage =
                        new Windows.UI.Xaml.Media.Imaging.BitmapImage();

                    bitmapImage.SetSource(fileStream);
                    displayImage.Source = bitmapImage;

                    // Set the data context for the page.
                    this.DataContext = file;
                }
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

照片页面保存状态是

protected override void SaveState(Dictionary<String, Object> pageState)
{
    if (!String.IsNullOrEmpty(mruToken))
    {
        pageState["mruToken"] = mruToken; 
    }
}
Run Code Online (Sandbox Code Playgroud)

我注意到导航到页面状态时始终为null.有任何想法吗?

小智 5

启用NavigationCacheMode页面的属性并添加NavigationCacheMode="Enabled"

要么

按属性面板启用它.