简体   繁体   English

C# Xamarin Forms 代码在加载时不执行但在按钮单击时执行

[英]C# Xamarin Forms Code not executing when loading but executing on button click

I have the same exact code running on Page opening and Button click.我在打开Page和单击Button时运行了相同的代码。 This is the code on load:这是加载代码:

[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");
        }
    });
}

and this is the button click:这是按钮点击:

[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");
    }        
}

I tried a try...catch to try to get any errors but nothing.我尝试了try...catch以尝试获取任何错误,但什么也没有。 It has to do with this line i guess but I can not seem to understand what this is;我猜这与这条线有关,但我似乎无法理解这是什么; Application.Current.MainPage = new MainPage(); . . Nothing is executed after that line.在该行之后没有执行任何操作。 This happened after I updated to latest Xamarin.Forms version.这发生在我更新到最新Xamarin.Forms版本之后。

Edit: The page is called through MainPage after check to perform login编辑:检查后通过MainPage调用该页面以执行登录

    if (GlobalVars.loginProfilJsonObject == null)
    {
        Task.Run(async () =>
        {
            await Navigation.PushAsync(new LoginPage());
        });
    }

Try using something like this:尝试使用这样的东西:

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 method executed after the page is displayed.页面显示后执行的 OnAppearing 方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM