我正在尝试显示 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()
在后台工作完成后将执行编码回主线程。这并不总是必要的,但这是一种很好的做法。
关于c# - 为什么事件指示器在 Xamarin.forms 中不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36008055/