MessagingCenter和NavigationService使用反射

问题描述 投票:0回答:1

我正在寻求改进在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;                    
        }

        ...

    });

}
xamarin mvvm xamarin.forms navigation messaging
1个回答
0
投票

我会给您一些有关使用MessagingCenter时如何使代码可读的想法。

First,您可以具有实现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实现这一目标。希望这会有所帮助。

© www.soinside.com 2019 - 2024. All rights reserved.