首页 > 解决方案 > 导航到 button_clicked 中的另一个页面时出现 Xamarin.Forms 错误

问题描述

在我的 Xamarin.Forms 项目中,我有一个用于 Android 的 SplashScreen 和一个用于 IOS 的 AppDelegate,它们检查一些条件,然后将一些数据传递给 App.xaml.cs 。然后 :

public App(string isLogin)
        {
            InitializeComponent();

            if (isLogin == "Nologin")
                App.Current.MainPage = new LoginPage();
            else
            {
                switch (isLogin)
                {
                    case "Update": 
                            App.Current.MainPage = new MessagePage("Some Message");
                        break;

                    case "Internet":
                        App.Current.MainPage = new MessagePage("Some Message");
                        break;

                    default:
                        App.Current.MainPage = new MainPage(isLogin);
                        break;
                }
            }


        }

现在在 MessagePage 我有这个:

private async void RefreshButton_Clicked(object sender, EventArgs e)
{
    string result = await AppStart.DoStartAsync().ConfigureAwait(false);

        if (result == "Login")
           await Navigation.PushAsync(new LoginPage());
}

显示此错误:

System.InvalidOperationException: 'PushAsync 在 Android 上不受全球支持,请使用 NavigationPage。'

如果我使用这个:

if (result == "Login")
    Application.Current.MainPage = new NavigationPage(new LoginPage());

显示此错误:

Android.Util.AndroidRuntimeException:'只有创建视图层次结构的原始线程才能触摸其视图。

我能做些什么 ?

标签: c#androidxamarin.formsonclick

解决方案


根据您的错误消息。 Android.Util.AndroidRuntimeException: 'Only the original thread that created a view hierarchy can touch its views.

此问题与您更新不在 UI 线程(主线程)中的视图有关,您应该将更新视图代码包装起来Device.BeginInvokeOnMainThread(Action)以确保任何 UI 更新都发生在正确的线程上。

Device.BeginInvokeOnMainThread(
 async () => { 
     await Navigation.PushAsync(new LoginPage());
 });

推荐阅读