简体   繁体   中英

Universal Apps Save and Load Settings

I have a problem with Save and Load Settings in Universal Apps. I type this code:

enter class Setting
{
    public static Kolor Read()
    {
        var localSettings = Windows.Storage.ApplicationData.Current.LocalSettings;

        byte _red = (byte)localSettings.Values["R"];
        byte _green = (byte)localSettings.Values["G"];
        byte _blue = (byte)localSettings.Values["B"];

        return new Kolor(_red, _green, _blue);
    }

    public static void Save(Kolor kolor)
    {
        var localSettings = Windows.Storage.ApplicationData.Current.LocalSettings;
        localSettings.Values["R"] = kolor.R;
        localSettings.Values["G"] = kolor.G;
        localSettings.Values["B"] = kolor.B;
    }
}

When I try to start apps, debuger show me NullReferenceException in:

enter byte _red = (byte)localSettings.Values["R"];

Someone can help me?

I think your issue is coming from the value that does not exist in the LocalSettings , so first check it exists.

public static Kolor Read()
{
    byte _red = GetByte("R");
    byte _green = GetByte("G");
    byte _blue = GetByte("B");

    return new Kolor(_red, _green, _blue);
}

private static byte GetByte(string key)
{
     if (!ApplicationData.Current.LocalSettings.Values.ContainsKey(key))
     {
         return default(byte);
     }
     return (byte)(ApplicationData.Current.LocalSettings.Values[key]);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM