我正在尝试使用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);
}
}发布于 2017-09-01 12:40:44
这是Xamarin.Forms版本2.3.3.175中的一个错误。要修复此错误,请安装早期版本的Xamarin.Forms。我使用2.3.0.107版本运行我的应用程序。
2.3.3.175版中的错误应在2.3.4-pre1版中修复。
https://stackoverflow.com/questions/45991938
复制相似问题