我已经阅读了多篇关于导航和使用棱镜传递参数的文章。但是,我尝试的任何内容都不会在更改页面时触发OnNavigatingTo方法。
我的目标是将一个简单的参数从Login Page传递给MultifactorAuthage。
如果我尝试在OnNavigatingTo方法中获取参数,那么应用程序将不会因某种原因更改页面。它将触及断点并保持在LoginPage上。
我目前正在使用带有Prism 7.1的Xamarin Forms 3.6。
这是我的一些代码:
LoginPageViewModel
public LoginPageViewModel(INavigationService navigationService, IPushNotification pushNotification)
{
_navigationService = navigationService;
LoginCommand = new DelegateCommand(BeginLoginAsync);
}
private async void BeginLoginAsync()
{
await _navigationService.NavigateAsync("MultifactorAuthPage", new NavigationParameters("PhoneNumber=9999999999"));
}
MultifactorAuthViewModel
public class MultifactorAuthPageViewModel : ViewModelBase, INavigationAware
{
INavigationService _navigationService;
public MultifactorAuthPageViewModel(INavigationService navigationService)
{
_navigationService = navigationService;
}
private override void OnNavigatingTo(INavigationParameters parameters)
{
}
private override void OnNavigatedFrom(INavigationParameters parameters)
{
}
private override void OnNavigatedTo(INavigationParameters parameters)
{
PhoneNumber = Convert.ToInt32(parameters["PhoneNumber"]);
}
}
ViewModelBase
public class ViewModelBase : BindableBase, INavigationAware
{
public ViewModelBase()
{
}
public virtual void OnNavigatedFrom(INavigationParameters parameters)
{
}
public virtual void OnNavigatedTo(INavigationParameters parameters)
{
}
public virtual void OnNavigatingTo(INavigationParameters parameters)
{
}
}
我试过的一些资源:
https://prismlibrary.github.io/docs/xamarin-forms/navigation/passing-parameters.html https://xamgirl.com/prism-in-xamarin-forms-step-by-step-part-2/ https://github.com/PrismLibrary/Prism-Samples-Forms/tree/master/ContosoCookbook
你的BeginLoginAsync
方法显然是异步的。因此,您还需要将该命令实例化为异步。试试这个:
public LoginPageViewModel(INavigationService navigationService, IPushNotification pushNotification)
{
_navigationService = navigationService;
LoginCommand = new DelegateCommand(async () => await BeginLoginAsync());
}
你还需要改变BeginLoginAsync
方法才能返回Task
而不是void
。
private async Task BeginLoginAsync()
{
await _navigationService.NavigateAsync("MultifactorAuthPage", new NavigationParameters("PhoneNumber=9999999999"));
}
那你应该没问题。
编辑:如果你必须等待并且不要忘记调用基本方法,也尝试将此方法签名更改为异步:
public override async void OnNavigatingTo(INavigationParameters parameters)
{
...
base.OnNavigatingTo(parameters);
}
希望它有帮助和快乐的编码!
事实证明,由于int值溢出,它无声地失败。无声的例外是杀手