PhoneApplicationService.Current.State equivalent in windows 8

∥☆過路亽.° 提交于 2019-12-06 12:19:25

问题


I am looking for equivalent class in Windows 8.x. API for PhoneApplicationService.Current.State which we found in Windows Phone API.

Basically, I am trying to persist simple object data between pages with in session. Or is there any other option in Windows 8 to achieve this?


回答1:


I won't recommend using the State, it's much easier to use just IsolatedStorage for preserving data both between sessions and pages as well, to keep is simple.
All data should be saved in ApplicationData.Current.LocalSettings or IsolatedStorageSettings.ApplicationSettings in case they are simple objects like string, bool, int.

// on Windows 8
// input value
string userName = "John";

// persist data
ApplicationData.Current.LocalSettings.Values["userName"] = userName;

// read back data
string readUserName = ApplicationData.Current.LocalSettings.Values["userName"] as string;

// on Windows Phone 8
// input value
string userName = "John";

// persist data
IsolatedStorageSettings.ApplicationSettings["userName"] = userName;

// read back data
string readUserName = IsolatedStorageSettings.ApplicationSettings["userName"] as string;

Complex objects like lists of ints, strings, etc. should be saved in ApplicationData.Current.LocalFolder possibly in JSON format (you need JSON.net package from NuGet):

// on Windows 8
// input data
int[] value = { 2, 5, 7, 9, 42, 101 };

// persist data
string json = JsonConvert.SerializeObject(value);
StorageFile file = await ApplicationData.Current.LocalFolder.CreateFileAsync("myData.json", CreationCollisionOption.ReplaceExisting);
await FileIO.WriteTextAsync(file, json);

// read back data
string read = await PathIO.ReadTextAsync("ms-appdata:///local/myData.json");
int[] values = JsonConvert.DeserializeObject<int[]>(read);


// on Windows Phone 8
// input data
int[] value = { 2, 5, 7, 9, 42, 101 };

// persist data
string json = JsonConvert.SerializeObject(value);
StorageFile file = await ApplicationData.Current.LocalFolder.CreateFileAsync("myData.json", CreationCollisionOption.ReplaceExisting);
using (Stream current = await file.OpenStreamForWriteAsync())
{
    using (StreamWriter sw = new StreamWriter(current))
    {
        await sw.WriteAsync(json);
    }
}

// read back data
StorageFile file2 = await ApplicationData.Current.LocalFolder.GetFileAsync("myData.json");
string read;
using (Stream stream = await file2.OpenStreamForReadAsync())
{
    using (StreamReader streamReader = new StreamReader(stream))
    {
        read = streamReader.ReadToEnd();
    }
}
int[] values = JsonConvert.DeserializeObject<int[]>(read);


来源:https://stackoverflow.com/questions/19886107/phoneapplicationservice-current-state-equivalent-in-windows-8

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!