导航到button_clicked中的另一个页面时,Xamarin.Forms错误

时间:2020-05-11 10:33:02

标签: c# android xamarin.forms onclick

在我的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:'Android上不全局支持PushAsync,请使用NavigationPage。'

如果我使用这个:

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

显示此错误:

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

我该怎么办?

1 个答案:

答案 0 :(得分:0)

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

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

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