1

Windows 8.x で同等のクラスを探しています。Windows Phone API で見つけた PhoneApplicationService.Current.State の API。

基本的に、セッション中のページ間で単純なオブジェクト データを永続化しようとしています。または、これを実現するための Windows 8 の他のオプションはありますか?

4

1 に答える 1

3

State の使用はお勧めしません。IsolatedStorage だけを使用して、セッション間とページ間の両方でデータを保持する方がはるかに簡単で、維持も簡単です。string、bool、int などの単純なオブジェクトの場合は、 すべてのデータをApplicationData.Current.LocalSettingsまたはIsolatedStorageSettings.ApplicationSettings
に 保存する必要があります。

// 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、文字列などのリストのような複雑なオブジェクトは、おそらく 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);
于 2013-11-10T11:12:32.930 に答える