我希望改进我用Xamarin.Forms开发的移动应用程序。
我的功能如下:应用程序的onResume我想要重新加载用户所在的页面。
目前,我使用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;
}
...
});
}发布于 2019-11-14 16:23:28
我会给你一些在使用MessagingCenter时如何让你的代码变得可读的想法。
对于第一个,您可以有一个实现MessagingCenter.Subscribe的BasePage和一个名为loadData的方法
public partial class BasePage : ContentPage
{
public BasePage()
{
MessagingCenter.Subscribe<App, string>(this, "Hi", (sender, arg) =>
{
// Do something whenever the "Hi" message is received
loadData();
});
}
public virtual void loadData()
{
}
}然后,当您创建一个在应用程序恢复时需要刷新的新页面时,您可以使该页面继承BasePage类型:
public partial class MainPage : BasePage
{
public MainPage()
{
InitializeComponent();
loadData();
}
public override void loadData()
{
base.loadData();
Console.WriteLine("loadData");
}
}和xaml:
<?xml version="1.0" encoding="utf-8" ?>
<bases:BasePage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:d="http://xamarin.com/schemas/2014/forms/design"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:bases="clr-namespace:App52"
mc:Ignorable="d"
x:Class="App52.MainPage">
</bases:BasePage>因此,您不必在每个页面中实现MessagingCenter.Subscribe,这些都可以在BasePage中进行管理。
我不熟悉reflection,所以可能不能通过reflection帮助你实现它。希望这能有所帮助。
https://stackoverflow.com/questions/58850972
复制相似问题