2
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"]);

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

为什么内存/存储/任何东西都不能保存我的值?

4

1 回答 1

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;
    }

}
于 2013-06-26T11:35:35.033 回答