silverlight - 应用程序退出后独立存储应用程序设置不会保留

标签 silverlight windows-phone-7 c#-4.0 isolatedstorage

我在使用 WP7 独立存储和应用程序设置时遇到了大问题。 我一直使用 Adam Nathan 的 101 个 Windows Phone 7 应用程序第 1 卷中的代码作为基础。

我有一个设置页面,可以在其中更改值,并且当应用程序仍在运行时,这些值仍保持事件状态,并且一切正常。但是,一旦应用程序在我的开发者手机上退出,这些信息就会丢失,并且应用程序会以默认设置重新启动。

我不知道为什么这些值(value)观没有持续存在。任何帮助将不胜感激。

这是我得到的代码,来自 adam nathan 的新书。我在 Twitter 上给他发了一条消息,他说这与不可序列化的数据类型有关。我对此进行了研究,但我只使用了 double 和 bool 值。

public class Setting<T>
{
    string name;
    T value;
    T defaultValue;
    bool hasValue;

    public Setting(string name, T defaultValue)
    {
        this.name = name;
        this.defaultValue = defaultValue;
    }

    public T Value
    {
        get
        {
            //checked for cached value
            if (!this.hasValue)
            {
                //try to get value from isolated storage
                if (IsolatedStorageSettings.ApplicationSettings.TryGetValue(this.name, out this.value))
                {
                    //not set yet
                    this.value = this.defaultValue;
                    IsolatedStorageSettings.ApplicationSettings[this.name] = this.value;
                }

                this.hasValue = true;
            }

            return this.value;
        }

        set
        {
            //save value to isolated storage
            IsolatedStorageSettings.ApplicationSettings[this.name] = value;
            this.value = value;
            this.hasValue = true;
        }
    }

    public T DefaultValue
    {
        get { return this.defaultValue; }
    }

    //clear cached value;
    public void ForceRefresh()
    {
        this.hasValue = false;
    }
}

进一步发展:

退出应用程序时我收到此错误:

mscorlib.dll 中发生了“System.IO.IsolatedStorage.IsolatedStorageException”类型的第一次机会异常

<小时/>

发现错误:我是个白痴,漏掉了一个感叹号!来自 trygetvalue 部分。

最佳答案

您能否发布您的存储代码,以便我们准确了解发生了什么情况?如果没有该代码,这里是我用来将设置保存到本地存储的代码:

IsolatedStorageSettings isoStoreSettings = IsolatedStorageSettings.ApplicationSettings;
if (isoStoreSettings.Contains(key))
{
    isoStoreSettings[key] = value;
}
else
{
    isoStoreSettings.Add(key, value);
}
isoStoreSettings.Save();

我的猜测是,您缺少最后一行,该行将对隔离存储设置的更改提交到物化隔离存储,而不是仅将它们保留在内存中。如果不是这种情况,请使用代码编辑您的帖子,以便我们提供帮助。

关于silverlight - 应用程序退出后独立存储应用程序设置不会保留,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6066440/

相关文章:

windows-phone-7 - wp7 滚动查看器列表框不工作

c# - 使用 java 和 WP7 进行 AES 加密

c# - 使用 MVVM 在 Silverlight 3 DataGrid 中编辑新添加的行

Silverlight 5 访问冲突异常

c# - 如何在 Windows Phone 7 中检查 3G、wifi、EDGE、蜂窝网络?

c# - 向后移植 C# 内插字符串运算符 $

c# - 我们如何为窗口创建单例实例?

c# - 以 2 位精度存储 double

c# - 检测何时设置了 Application.Current.RootVisual (Silverlight)

wpf - WPF和SilverLight Design值得学习吗