c# - 为什么事件指示器在 Xamarin.forms 中不起作用?

标签 c# xamarin xamarin.forms portable-class-library

我正在尝试显示 ActivityIndi​​cator 在我尝试更新数据库上的列字段时按下按钮后,它没有出现?有什么问题?

关于以下我的代码:

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/

相关文章:

c# - 在 C# 中使用 Visual Studio 通过 mySQL 将数据插入数据库

c# - Metro App - 如何检测是否使用 Live ID 或本地帐户登录

xamarin - 更改 DatePicker [Xamarin.Forms] 的颜色

c# - 在 Provider Ninject 中检索自定义绑定(bind)参数

ios - 每日通知

ios - 在 Xamarin iOS 的 UIActivityIndi​​catorView 中隐藏指示器

ios - Xamarin Forms : ImageSource. FromUri 不显示

ios - 如何选择/设置用于 Visual Studio App Center 项目的图像?

android - Xamarin Forms QR 代码扫描仪黑屏

c# - C# 中的 mySQL + LINQ to SQL