2016-03-15 131 views
2

我想显示ActivityIndicator当我试图更新列上的数据库时,按下按钮后,它不出现?问题是什么?活动指示灯不工作Xamarin.forms

在下面我的代码:

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 
       } 
      }; 
+0

样?它是一个Bindable属性? – StarterPack

+0

ProcessToCheckOut是按钮..我应该添加一个属性?! –

+0

@StarterPack IsBusy是内置的。它用于打开和关闭状态栏活动图标 - 但你也可以在你自己的代码中使用它,就像在这里完成 –

回答

4

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()一旦后台工作完成编组执行回主线程。这并不总是必要的,但这是很好的做法。

+0

非常感谢很好的回答:) –

+0

嗨,我只是想分享一个稍微不同的方法,我发现和在这里回答:http://stackoverflow.com/a/43119987/1605873 –

0

您可以使用Xamarin.Forms ACR.UserDialogs,你会发现是很容易的:

UserDialogs.Instance.ShowLoading("Loading..."); 
UserDialogs.Instance.HideLoading(); 

看你怎么定义IsBusy在acr github