我现在只有几天使用Xamarin Forms并尝试在MVVM架构中执行此操作。如何在if if语句之后加载下一页(Home / Menu Page)?这样我做得对吗?我的指示是应该有电子邮件验证,密码不能少于6个字符。
public User User
{
get { return user; }
set { user = value; }
}
public Command LoginCommand
{
get
{
return new Command(() =>
{
bool usr = string.IsNullOrEmpty(User.Username);
bool pass = string.IsNullOrEmpty(User.Password);
if (usr && pass)
{
App.Current.MainPage.DisplayAlert("Error", "Please enter Credentials", "OK");
}
else
{
if (EmailRegex.IsMatch(User.Username))
{
if (pass)
{
App.Current.MainPage.DisplayAlert("Error", "Please enter password!", "OK");
}
else if (User.Password.Length < 6)
{
App.Current.MainPage.DisplayAlert("Error", "Password must be at least 6 characters", "OK");
}
else
{
//load menu page
}
}
else
{
App.Current.MainPage.DisplayAlert("Error", "Email is not a valid email address!", "OK");
}
}
});
}
}
Regex EmailRegex = new Regex(@ "^([\w\.\-]+)@([\w\-]+)((\.(\w){2,3})+)$");
public bool ValidateEmail(string email)
{
if (string.IsNullOrWhiteSpace(email))
return false;
return EmailRegex.IsMatch(email);
}
}
}
您可以在MVVM
中使用以下代码进行导航:
public INavigation Navigation { get; set;}
public YourViewModel(INavigation navigation)
{
this.Navigation = navigation;
this.YourButtonClick= new Command(async () => await GotoPage2());
}
public async Task GotoPage2()
{
/////
await Navigation.PushAsync(new Page2());
}
确保在App.xaml.cs中将MainPage设置为导航页面
MainPage = new NavigationPage(new Page1());
然后用
Navigation.PushAsync(new Page2());