无法在新主页上打开模式

时间:2019-03-30 23:02:16

标签: xamarin xamarin.forms

此代码完全演示了看起来像是错误的错误。顺序是...

  1. 应用打开
  2. 已创建默认主页。
  3. 弹出登录框。
  4. 登录框已关闭。 (点击页面进行模拟)
  5. 已创建新主页。
  6. 弹出登录框。(单击页面进行模拟)
  7. 异常...无法访问已处置的对象。

有什么想法吗?

using System;
using System.Threading.Tasks;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;

[assembly: XamlCompilation(XamlCompilationOptions.Compile)]
namespace test333
{
    public class Main1 : ContentPage
    {
        public Main1()
        {
            var btn = new Button();

            btn.Clicked += (sender, e) =>
            {
                MessagingCenter.Send<object>(this, "LoginLogout");
                Navigation.PopModalAsync();
            };
            Content = btn;
        }
    }

    public partial class App : Application
    {
        public App()
        {
            InitializeComponent();

            MainPage = new Main1 { BackgroundColor = Color.Red };

            MessagingCenter.Subscribe<object>(this, "LoginLogout", s =>
                Device.BeginInvokeOnMainThread(async () => await HandleLogOut()));

            HandleLogOut();
        }

        bool login = true;

        async Task HandleLogOut()
        {
            if (login)
            {
                await MainPage.Navigation.PushModalAsync(new Main1 { BackgroundColor = Color.Orange });
            }
            else
            {
                MainPage = new Main1 { BackgroundColor = Color.Green };
            }

            login = !login;
        }
    }
}

1 个答案:

答案 0 :(得分:0)

我认为问题发生在步骤6:Login box popped up.(Click on page to simulate)

看看btn.clicked中的以下代码:

btn.Clicked += (sender, e) =>
            {
                MessagingCenter.Send<object>(this, "LoginLogout");

                Console.WriteLine("popAction");
                Navigation.PopModalAsync();
            };

并处理注销:

 async Task HandleLogOut()
        {
            if (login)
            {
                await MainPage.Navigation.PushModalAsync(new Main1 { BackgroundColor = Color.Orange });
                Console.WriteLine("PushModalAction");
            }
            else
            {
                MainPage = new Main1 { BackgroundColor = Color.Green };
            }

            login = !login;
        }

我在您的代码中打印了popActionPushAction,您会发现popActionPushAction之前执行。

解决方案:

您应在popAction完成后执行pushModalAction

我将Navigation.PopModalAsync();btn.clicked移到了HandleLogOut,然后运行良好。

   btn.Clicked += async (sender, e) =>
            {
                MessagingCenter.Send<object>(this, "LoginLogout");                            
            };

在句柄注销中:

async Task HandleLogOut()
{
    if (login)
    {
        Console.WriteLine("PushModalAction");
        await MainPage.Navigation.PushModalAsync(new Main1 { BackgroundColor = Color.Orange });

        Console.WriteLine("popAction");
        MainPage.Navigation.PopModalAsync();                

    }
    else
    {
        MainPage = new Main1 { BackgroundColor = Color.Green };
    }

    login = !login;
}