Windows 8中的PhoneApplicationService.Current.State等价物

时间:2013-11-10 03:57:08

标签: c# windows-8 windows-phone-8

我正在寻找Windows 8.x中的等效类。我们在Windows Phone API中找到的PhoneApplicationService.Current.State API。

基本上,我试图在会话中的页面之间保留简单的对象数据。 或者Windows 8中是否还有其他选项可以实现此目的?

1 个答案:

答案 0 :(得分:3)

我不推荐使用State,只使用IsolatedStorage来保存会话和页面之间的数据也更容易,保持简单。
所有数据都应保存在 ApplicationData.Current.LocalSettings IsolatedStorageSettings.ApplicationSettings 中,以防它们是简单对象,如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;

像int,string等列表这样的复杂对象应该以JSON格式保存在 ApplicationData.Current.LocalFolder 中(你需要来自NuGet的JSON.net包):

// 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);