Вопрос

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

and then after restarting the app in Visual Studio:

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

it prints nothing (which means the Object is null).

Why does that happen?

When I do it like this:

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

it prints successfully, but the point of storage is that the values being saved are available after a restart of the app....

Why is the memory/storage/whatever not saving my values?

Это было полезно?

Решение

When you want to add a value, you have to call localSettings.Values.Add("key", "test1")

I'm using the following class as a settings helper:

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

}
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top