Quantcast
Channel: Xamarin.Forms — Xamarin Community Forums
Viewing all articles
Browse latest Browse all 89864

System.Reflection.TargetInvocationException on MessagingCenter.Send

$
0
0

I'm trying to build simple navigation using MessagingCenter but I'm receiving System.Reflection.TargetInvocationException when I pressed the back button (hardware button).

Here is how I get the error;

After app load,
I hit the back button (hardware button)
Then after the app got minimized, I open it in recent app
After that, I click on Login then I got this error:

Unhandled Exception:

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

pointing on

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

in Login Method in LoginPage.xaml.cs

PS: The code works well if I don't hit the back button (hardware button)

Here is the code:

        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);
    }
}

Viewing all articles
Browse latest Browse all 89864

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>