为什么活动指示器在 Xamarin.Forms 中不起作用



我正在尝试显示ActivityIndicator 当我尝试更新数据库上的列字段时按下按钮后,它没有出现?问题出在哪里?

在以下"我的代码"上:

ActivityIndicator ai = new ActivityIndicator()
            {
                HorizontalOptions = LayoutOptions.CenterAndExpand,
                Color = Color.Black
            };
            ai.IsRunning = true;
            ai.IsEnabled = true;
            ai.BindingContext = this;
            ai.SetBinding(ActivityIndicator.IsVisibleProperty, "IsBusy");
            ProcessToCheckOut = new Button { Text = "Set Inf" };
            ProcessToCheckOut.Clicked += (object sender, EventArgs e) =>
            {
                this.IsBusy = true;
                UserUpdateRequest user=new UserUpdateRequest();
                user.userId = CustomersPage.ID;
                appClient.UpdateInfo(user);                  
                this.IsBusy = false;
                Navigation.PushAsync(new CheckoutShippingAddressPage(appClient));
            };
         Content = new StackLayout
            {
                Children={
                tb,
                ai,
                ProcessToCheckOut
                }
            };

this.IsBusy=true;this.IsBusy=false; 之间的代码都不是异步的。因此,正在发生的事情是您启用指示器,但随后继续在主线程上工作,然后在 UI 有机会更新之前禁用指示器。

要解决此问题,您需要将appClient.UpdateInfo(user)放入异步代码块中(以及 PushAsync 和禁用活动指示器,可能还有其他一些代码)。如果您没有异步版本的UpdateInfo()那么您可以将其推送到后台线程中......假设它所做的任何工作实际上都可以安全地在后台线程中运行。

ProcessToCheckOut.Clicked += (object sender, EventArgs e) =>
{
    this.IsBusy = true;
    var id = CustomersPage.ID;
    Task.Run(() => {
        UserUpdateRequest user=new UserUpdateRequest();
        user.userId = id;
        appClient.UpdateInfo(user);
        Device.BeginInvokeOnMainThread(() => {
            this.IsBusy = false;
            Navigation.PushAsync(new CheckoutShippingAddressPage(appClient));
        });
    });
};

请注意,我还使用 Device.BeginInvokeOnMainThread() 在后台工作完成后将执行封送回主线程。这并不总是必要的,但这是很好的做法。

你的 endoint 必须是 getasync 或 postasync with await

最新更新