MessagingCenter.Send上的System.Reflection.TargetInvocationException

时间:2017-09-01 00:50:49

标签: c# xamarin xamarin.forms

我尝试使用MessagingCenter构建简单的导航,但是当我按下后退按钮(硬件按钮)时,我正在接收System.Reflection.TargetInvocationException

以下是我收到错误的方法;

应用加载后,
我按下后退按钮(硬件按钮)
然后在应用程序最小化后,我在最近的应用程序中打开它 之后,我点击Login然后我收到了这个错误:

Unhandled Exception:

System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation.

指向

MessagingCenter.Send<object>(this, App.EVENT_LAUNCH_MAIN_PAGE);

在LoginPage.xaml.cs中的登录方法中

PS:如果我没有点击后退按钮(硬件按钮),代码就可以正常运行

以下是代码:

App.xaml.cs
public partial class App : Application
{
    public static string EVENT_LAUNCH_LOGIN_PAGE = "EVENT_LAUNCH_LOGIN_PAGE";
    public static string EVENT_LAUNCH_MAIN_PAGE = "EVENT_LAUNCH_MAIN_PAGE";

    public App()
    {
        InitializeComponent();

        MainPage = new App3.LoginPage();

        MessagingCenter.Subscribe<object>(this, EVENT_LAUNCH_LOGIN_PAGE, SetLoginPageAsRootPage);
        MessagingCenter.Subscribe<object>(this, EVENT_LAUNCH_MAIN_PAGE, SetMainPageAsRootPage);
    }

    private void SetLoginPageAsRootPage(object sender)
    {
        MainPage = new NavigationPage(new LoginPage());
    }

    private void SetMainPageAsRootPage(object sender)
    {
        MainPage = new NavigationPage(new App3.MainPage());
    }

    protected override void OnStart()
    {
        // Handle when your app starts
    }

    protected override void OnSleep()
    {
        // Handle when your app sleeps
    }

    protected override void OnResume()
    {
        // Handle when your app resumes
    }
}

LoginPage.xaml.cs
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class LoginPage : ContentPage
{
    public Command LoginCommand { get; }

    public LoginPage()
    {
        InitializeComponent();

        LoginCommand = new Command(() => Login());

        Button btn = new Button { Text = "Login", Command = LoginCommand };

        Content = new StackLayout
        {
            Children =
            {
                btn
            }
        };
    }

    public void Login()
    {
        MessagingCenter.Send<object>(this, App.EVENT_LAUNCH_MAIN_PAGE);
    }
}

MainPage.xaml.cs
public partial class MainPage : ContentPage
{
    public MainPage()
    {
        InitializeComponent();

        ToolbarItems.Add(new ToolbarItem("Logout", "", () => Logout()));
    }

    public void Logout()
    {
        MessagingCenter.Send<object>(this, App.EVENT_LAUNCH_LOGIN_PAGE);
    }
}

1 个答案:

答案 0 :(得分:0)

这是Xamarin.Forms版本2.3.3.175中的错误。要修复此错误,请安装早期版本的Xamarin.Forms。我的应用程序运行版本为2.3.0.107。

版本2.3.3.175中的错误应在版本2.3.4-pre1中修复。