简体   繁体   中英

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. 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. 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.

Edit: The page is called through MainPage after check to perform login

    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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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