[C#Xamarin Forms Code加载时未执行,而是单击按钮时执行

问题描述 投票:0回答:1

我在打开Page和单击Button时具有相同的确切代码。这是加载代码:

[Obsolete]
public LoginPage()
{
    Task.Run(async () =>
    {
        User results = await LoginService.Login(username.Text.Trim(), password.Text.Trim());
        if (results != null)
        {
            GlobalVars.loginProfilJsonObject = results;
            Application.Current.MainPage = new MainPage();
            Console.WriteLine("Not executing");
        }
        else
        {
            await DisplayAlert("Error", "Wrong email address or password", "OK");
        }
    });
}

这是单击按钮:

[Obsolete]
async void OnClicked(object sender, EventArgs e)
{
    User results = await LoginService.Login(username.Text.Trim(), password.Text.Trim());
    if (results != null)
    {
        GlobalVars.loginProfilJsonObject = results;
        Application.Current.MainPage = new MainPage();
    }
    else
    {
        await DisplayAlert("Error", "Wrong email address or password", "OK");
    }        
}

我尝试使用try...catch尝试获取任何错误,但一无所获。我想这与这条线有关,但我似乎无法理解这是什么。 Application.Current.MainPage = new MainPage();。在该行之后什么也不会执行。我更新到最新的Xamarin.Forms版本后,便发生了这种情况。

编辑:检查执行登录后通过MainPage调用页面

    if (GlobalVars.loginProfilJsonObject == null)
    {
        Task.Run(async () =>
        {
            await Navigation.PushAsync(new LoginPage());
        });
    }
c# xamarin xamarin.forms xamarin.android navigation
1个回答
1
投票

尝试使用类似这样的内容:

protected override async void OnAppearing()
{
    base.OnAppearing();

    User results = await LoginService.Login(username.Text.Trim(), password.Text.Trim());
    if (results != null)
    {
        GlobalVars.loginProfilJsonObject = results;
        Application.Current.MainPage = new MainPage();
        Console.WriteLine("Not executing");
    }
    else
    {
        await DisplayAlert("Error", "Wrong email address or password", "OK");
    }
}

显示页面后执行的OnAppearing方法。

© www.soinside.com 2019 - 2024. All rights reserved.