C# Xamarin表单用户登录和注销不适用于Android
我有登录和注销用户的问题。若我第一次点击按钮登录,然后点击注销,一切正常,但若我再次启动应用程序,我只有一个空白页面,我必须卸载应用程序,它的工作方式和第一次一样 App.cs代码:C# Xamarin表单用户登录和注销不适用于Android,c#,android,xamarin.forms,C#,Android,Xamarin.forms,我有登录和注销用户的问题。若我第一次点击按钮登录,然后点击注销,一切正常,但若我再次启动应用程序,我只有一个空白页面,我必须卸载应用程序,它的工作方式和第一次一样 App.cs代码: public App() { InitializeComponent(); if (!Current.Properties.ContainsKey("IsLoggedIn")) { Current.Properties["IsLoggedIn"] = false;
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();
}
问题在于
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();
}
}