在應用中一般會遇到用戶主動或被動存儲信息的狀況,當應用關閉後這些數據仍然會存儲在本地設備上,用戶下次從新激活應用時會自動加載這些數據。下面將經過一個小實例演示如何把用戶數據存儲到本地,首先在Windows 8 應用中建立兩個輸入框:姓名、年齡。ide
<StackPanel Grid.Row="1" Margin="120,30,0,0"> <StackPanel Orientation="Horizontal" Margin="0,20,0,20"> <TextBlock Text="Name: " Style="{StaticResource BasicTextStyle}" Width="50"/> <TextBox x:Name="nameInput" Width="200"/> </StackPanel> <StackPanel Orientation="Horizontal" Margin="0,20,0,20"> <TextBlock Text="Age: " Style="{StaticResource BasicTextStyle}" Width="50"/> <TextBox x:Name="ageInput" Width="200"/> </StackPanel> <StackPanel Orientation="Horizontal" Margin="0,20,0,20"> <Button Content="Save" Click="Save_Button_Click"/> <Button Content="Reset" Click="Reset_Button_Click"/> </StackPanel> </StackPanel>
打開MainPage .xaml.cs 爲了使用數據存儲API,先添加using Windows.Storage 命名空間。在MainPage中使用ApplicationData.LocalSettings屬性獲取到應用設置本地存儲空間。spa
ApplicationDataContainer localSettings = ApplicationData.Current.LocalSettings;
接下來在Save_Button_Click 事件中爲localSettings 設置兩個數值分別存儲Name 和Age 數據。code
private void Save_Button_Click(object sender, RoutedEventArgs e) { localSettings.Values["name"] = nameInput.Text; localSettings.Values["age"] = ageInput.Text; }
下面要作的就是在應用激活時將已經保存在本地的數據加載進來,在MainPage .xaml.cs 程序中已經有一個LoadState 方法用來加載應用數據或狀態,咱們能夠在這裏完成數據的加載工做。事件
protected override void LoadState(Object navigationParameter, Dictionary<String, Object> pageState) { if (localSettings.Values.ContainsKey("name")) { nameInput.Text = localSettings.Values["name"].ToString(); } if (localSettings.Values.ContainsKey("age")) { ageInput.Text = localSettings.Values["age"].ToString(); } }
本地數據存儲用於保存例如應用設置相關的重要信息,固然這些數據是留存本地設備中的,若是這些數據再也不使用時也能夠進行消除操做。以下代碼就是將以前的姓名和年齡信息進行刪除,數據刪除後從新激活應用將沒法加載。get
private void Reset_Button_Click(object sender, RoutedEventArgs e) { localSettings.Values.Remove("name"); localSettings.Values.Remove("age"); nameInput.Text = ""; ageInput.Text = ""; }