PhoneApplicationService的任务在于控制Windows Phone 7 application 在任何状态下的寿命,包括Application在idle阶段时该处理的任务,管理Application状态改变时触发的事件,常用来保存Application的状态和设置。
1.首先我们需要建一个PhoneApplicationService对象,用来管理状态。
PhoneApplicationService phoneAppServeice = PhoneApplicationService.Current;
2.在App.cs中添加俩个方法,用来加载Application状态和保存Application状态。
1)加载方法如下:
private void LoadState()
{
PhoneApplicationService phoneAppServeice = PhoneApplicationService.Current;
IsolatedStorageSettings settings = IsolatedStorageSettings.ApplicationSettings;
string myValue;
if (settings.TryGetValue<string>("MyValue",out myValue))
{
phoneAppServeice.State["MyValue"]=myValue;
}
}
2)保存方法如下:
private void SaveState()
{
PhoneApplicationService phoneAppServeice = PhoneApplicationService.Current;
IsolatedStorageSettings settings = IsolatedStorageSettings.ApplicationSettings;
if (phoneAppServeice.State.ContainsKey("MyValue"))
{
settings["MyValue"] = phoneAppServeice.State["MyValue"];
}
}
3.在App.cs事件中使用上诉俩个方法
private void Application_Launching(object sender, LaunchingEventArgs e)
{
LoadState();
}
private void Application_Activated(object sender, ActivatedEventArgs e)
{
LoadState();
}
private void Application_Deactivated(object sender, DeactivatedEventArgs e)
{
SaveState();
}
private void Application_Closing(object sender, ClosingEventArgs e)
{
SaveState();
}
4.在MainPage.xaml.cs中获取值和保存值
1)保存如下
private void myTextBox_TextChanged(object sender, TextChangedEventArgs e)
{
phoneAppServeice.State["MyValue"] = myTextBox.Text;
}
2)获取如下
private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
{
object myValue;
if (phoneAppServeice.State.ContainsKey("MyValue"))
{
if (phoneAppServeice.State.TryGetValue("MyValue", out myValue))
{
this.myTextBox.Text = myValue.ToString();
}
}
}
5.测试方法
1)启动Application,在文本域中输入数据。
2)按"back"键退出Application。
3)再次进入Application,你会看到你输入的数据是一致的。
4)再按"start"键退出Application。
5)再次进入和上诉3一样
这说明值保存成功!
效果图如下
6.代码下载