2013-11-10 23 views

回答

3

我不會推薦使用狀態,使用IsolatedStorage更容易在會話和頁面之間保存數據,以保持簡單。
所有數據應保存在ApplicationData.Current.LocalSettingsIsolatedStorageSettings.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; 

像整數的列表,字符串等複雜對象應儘可能以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);