【发布时间】:2019-11-14 06:51:16
【问题描述】:
我希望改进在 Xamarin.Forms 中开发的移动应用程序。
我的功能如下:onResume of the application 我要重新加载用户所在的页面。
目前我使用MessagingCenter来操作如下代码。
不幸的是,我的应用程序开始有很多页面,并且不再可读。
因此,我希望将我的类型 (viewModel) 作为导航服务的参数传递 - 我的研究将我引向反射的概念,但我不知道我的问题是否可以解决。
// App.xaml.cs
protected override void OnResume()
{
// Handle when your app resumes
Page currPage = ((NavigationPage)((MasterDetailPage)Application.Current.MainPage).Detail).CurrentPage;
MessagingCenter.Send<App, Page>(this, "Hi", currPage);
}
然后在我的 BaseViewModel 中:
// BaseViewModel.cs
public ViewModelBase()
{
DialogService = ViewModelLocator.Instance.Resolve<IDialogService>();
NavigationService = ViewModelLocator.Instance.Resolve<INavigationService>();
AuthenticationService = ViewModelLocator.Instance.Resolve<IAuthenticationService>();
MessagingCenter.Subscribe<App, Page>(this, "Hi", async (sender, arg) =>
{
// Do something whenever the "Hi" message is received
Type viewModel = NavigationService.GetViewModelTypeForPage(arg.GetType());
if(viewModel == typeof(AboutViewModel))
{
Debug.WriteLine("AboutViewModel");
await NavigationService.NavigateToAsync<AboutViewModel>();
return;
}
if (viewModel == typeof(CardViewModel))
{
Debug.WriteLine("CardViewModel");
await NavigationService.NavigateToAsync<CardViewModel>();
return;
}
...
});
}
【问题讨论】:
标签: xamarin mvvm xamarin.forms navigation messaging