我遇到登录和注销用户的问题。如果在第一次我点击按钮登录并点击退出后一切正常,但如果我再次启动应用程序我只有空白页面,我必须卸载应用程序thaht像第一种情况一样工作
App.cs代码:
public App()
{
InitializeComponent();
if (!Current.Properties.ContainsKey("IsLoggedIn"))
{
Current.Properties["IsLoggedIn"] = false;
if ((bool)Current.Properties["IsLoggedIn"] == false)
{
MainPage = new LoginPage();
}
else
{
MainPage = new NavigationPage(new MainPage());
}
}
}
登录页面:
async private void Button_Clicked_Login(object sender, EventArgs e)
{
Application.Current.Properties["IsLoggedIn"] = true;
await Application.Current.SavePropertiesAsync();
Application.Current.MainPage = new NavigationPage(new MainPage());
}
注销:
async private void Button_Clicked(object sender, EventArgs e)
{
Application.Current.Properties["IsLoggedIn"] = false;
await Application.Current.SavePropertiesAsync();
Application.Current.MainPage = new LoginPage();
}
答案 0 :(得分:2)
问题在于
if (!Current.Properties.ContainsKey("IsLoggedIn"))
在第一次启动应用时,您正在检查该属性是否存在。并且它不存在,所以它进入你的if语句。但是,然后,您分配该属性,并为下次启动if将始终失败。
我建议你把if语句改写成类似的东西:
if (!Current.Properties.ContainsKey("IsLoggedIn")) {
Current.Properties["IsLoggedIn"] = false;
await Application.Current.SavePropertiesAsync();
MainPage = new LoginPage();
} else {
if(Current.Properties["IsLoggedIn"] == true) {
MainPage = new NavigationPage(new MainPage());
} else {
MainPage = new LoginPage();
}
}