Win 8 LocalStorage设置未保存

时间:2013-06-26 11:14:53

标签: c# .net application-data

ApplicationDataContainer localSettings = ApplicationData.Current.LocalSettings;
localSettings.Values["stupidcrap"] = "test1";

然后在Visual Studio中重新启动应用程序后:

ApplicationDataContainer localSettings = ApplicationData.Current.LocalSettings;
Debug.WriteLine(localSettings.Values["stupidcrap"]);

它什么都不打印(这意味着Object为空)。

为什么会这样?

当我这样做的时候:

ApplicationDataContainer localSettings = ApplicationData.Current.LocalSettings;
localSettings.Values["stupidcrap"] = "test1";
Debug.WriteLine(localSettings.Values["stupidcrap"]);

它打印成功,但存储点是重新启动应用程序后保存的值可用....

为什么内存/存储/不保存我的值?

1 个答案:

答案 0 :(得分:7)

如果要添加值,则必须调用localSettings.Values.Add("key", "test1")

我使用以下类作为设置助手:

public class StorageSettingsApplication
{
    public StorageSettingsApplication()
    {
        try
        {
            localSettings = ApplicationData.Current.LocalSettings;
        }
        catch (Exception)
        {
        }
    }
    ApplicationDataContainer localSettings;
    publicTValue TryGetValueWithDefault<TValue>(string key, TValue defaultvalue)
    {
        TValue value;

        // If the key exists, retrieve the value.
        if (localSettings.Values.ContainsKey(key))
        {
            value = (TValue)localSettings.Values[key];
        }
        // Otherwise, use the default value.
        else
        {
            value = defaultvalue;
        }

        return value;
    }

    public bool AddOrUpdateValue(string key, object value)
    {
        bool valueChanged = false;

        // If the key exists
        //if (localSettings.Contains(Key))
        if (localSettings.Values.ContainsKey(key))
        {
            // If the value has changed
            if (localSettings.Values[key] != value)
            {
                // Store the new value
                localSettings.Values[key] = value;
                valueChanged = true;
            }
        }
        // Otherwise create the key.
        else
        {
            localSettings.Values.Add(key, value);
            valueChanged = true;
        }

        return valueChanged;
    }

}