2016-03-15 99 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