首页 > 解决方案 > 导航到 xamarin 表单中的下一页

问题描述

假设我在 Page_1 中,单击按钮必须导航到 Page_2.In Page_2 Api 调用必须完成。

MyIssue 是当我单击按钮时,它不会立即导航到 Page_2,而是等待 API 响应。

如何在不等待 APi 响应的情况下立即导航到 Page_2。

代码:

Page_1.cs

public partial class Page_1 : ContentPage
{
    public Page_1()
    {
        InitializeComponent();
    }
    private void Btn_click(object sender, EventArgs e)
    {
        Navigation.PushAsync(new Page_2());
    }

}

第2页:

public Page_2()
    {
        InitializeComponent();
    }
    protected override void OnAppearing()
    {
        HttpClient httpClient = new HttpClient();
        var obj = httpClient.GetAsync("//Api//").Result;
        if (obj.IsSuccessStatusCode)
        {

        }
    }

与预期相同的代码在 iOS 中运行良好

标签: c#xamarinxamarin.forms

解决方案


您可以将数据加载到其他任务中以防止阻塞 UI。

protected override void OnAppearing()
{
    Task.Run( () => LoadData());
    base.OnAppearing();
}

private async void LoadData()
{
    HttpClient httpClient = new HttpClient();
    var obj = await httpClient.GetAsync("//Api//");
    if (obj.IsSuccessStatusCode)
    {
        // If you need to set properties on the view be sure to use MainThread
        // otherwise you won't see it on the view.
        Device.BeginInvokeOnMainThread(() => Name = "your text";);
    }
}

推荐阅读