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

标签 c# windows-store-apps

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

Create your first Windows Store app using C# or Visual Basic

Part 3: Navigation, layout, and views

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

private void photoPageButton_Click(object sender, RoutedEventArgs e)
{
    this.Frame.Navigate(typeof(PhotoPage));
}

图片页面中的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;
                }
            }
        }
    }
}

图片页面保存状态为

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

我注意到导航到时页面状态始终为空。有什么想法吗?

最佳答案

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

通过属性面板启用它。

关于c# - 创建 Windows 8 应用程序时保存页面之间的状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16101523/

相关文章:

windows-runtime - Windows 商店应用程序中应用程序屏幕调整大小的黑色背景

c++ - 使用 C++ WRL 打开 UsbDevice - ERROR_INVALID_HANDLE

c# - Visual Studio 应用程序,XP 在某些标签的开头添加了一个额外的方 block 字符

c# - Entity Framework 试图插入错误的表?

c# - 如何在 C# 中匹配 URL?

windows - 将 node-webkit 应用程序打包为 ".appx"(适用于 Windows 8 商店)

uwp - 我们如何检测 Windows 应用商店应用程序中音频端点的变化?

windows-store-apps - Windows 10 应用商店应用程序中徽章 Logo 的用途是什么?

c# - File.OpenWrite 给出错误,而 FileStream(sFile, FileMode.Open, FileAccess.ReadWrite) 没有

c# - 如何在 ASP.NET Web api 中接收 json?