在开发windows phone 的时候我们一般都要保存用户端登陆信息,就像在做网页的时候,用session保存用户的登陆状态一个月,两个月,我们现在在做的是只要软件没有卸载,那么用户的用户名和密码会一直存在着,你下次进入软件的时候不用登陆了,这样大大的增加了用户的体验。废话不多说,来说下怎么做这个问题吧。
操作流程:
第一步:
在App.xaml.cs 中定义两个方法(要先添加引用using System.IO.IsolatedStorage;)
private void LoadState()
{
PhoneApplicationService phoneAppServeice = PhoneApplicationService.Current;
IsolatedStorageSettings settings = IsolatedStorageSettings.ApplicationSettings;
string StudentName;
if (settings.TryGetValue<string>("StudentName", out StudentName))
{
phoneAppServeice.State["StudentName"] = StudentName;
}
}
private void SaveState()
{
PhoneApplicationService phoneappserveice= PhoneApplicationService.Current;
IsolatedStorageSettings settings=IsolatedStorageSettings.ApplicationSettings;
if (phoneappserveice.State.ContainsKey("StudentName"))
{
settings["StudentName"] = phoneappserveice.State["StudentName"];
}
}
第二步
在页面自带的事件中调用这两个方法
// 应用程序启动(例如,从“开始”菜单启动)时执行的代码
// 此代码在重新激活应用程序时不执行
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();
}
第三步
在用户登录的时候保存用户的信息
void login_loginCompleted(object sender, ServiceReference1.loginCompletedEventArgs e)
{
if (e.Result == true)
{
//这里是登陆成功
phoneappserveice.State["StudentName"] = txtName.Text.ToString();
//登陆成功返回到上一个页面
MessageBox.Show("登录成功");
NavigationService.GoBack();
}
else
{
//这里是登陆失败
MessageBox.Show("用户名或密码错误");
}
}
第四步:读取用户的信息
protected override void OnNavigatedTo(NavigationEventArgs e)
{
base.OnNavigatedTo(e);
//页面加载的时候
if (phoneappserveice.State["StudentName"] != null)
{
StudentName.Text = phoneappserveice.State["StudentName"].ToString();
}
}
就这样就可以了。
在这里附加几张效果图