如何强制显示忙碌指示器?(WPF)

Unh*_*ppy 8 wpf mvvm

我创建了一个繁忙的指标 - 基本上是一个标志旋转的动画.我已将其添加到登录窗口并将Visibility属性绑定到我的viewmodel的BusyIndi​​catorVisibility属性.

当我单击登录时,我希望在登录发生时显示微调器(它调用Web服务来确定登录凭据是否正确).但是,当我将可见性设置为可见时,然后继续登录,在登录完成之前不会显示微调器.在Winforms旧式编码中,我会添加一个Application.DoEvents.如何让微调器出现在MVVM应用程序的WPF中?

代码是:

        private bool Login()
        {
            BusyIndicatorVisibility = Visibility.Visible;
            var result = false;
            var status = GetConnectionGenerator().Connect(_model);
            if (status == ConnectionStatus.Successful)
            {
                result = true;
            }
            else if (status == ConnectionStatus.LoginFailure)
            {
                ShowError("Login Failed");
                Password = "";
            }
            else
            {
                ShowError("Unknown User");
            }
            BusyIndicatorVisibility = Visibility.Collapsed;
            return result;
        }
Run Code Online (Sandbox Code Playgroud)

HCL*_*HCL 8

您必须使您的登录异步.您可以使用BackgroundWorker执行此操作.就像是:

BusyIndicatorVisibility = Visibility.Visible; 
// Disable here also your UI to not allow the user to do things that are not allowed during login-validation
BackgroundWorker bgWorker = new BackgroundWorker() ;
bgWorker.DoWork += (s, e) => {
    e.Result=Login(); // Do the login. As an example, I return the login-validation-result over e.Result.
};
bgWorker.RunWorkerCompleted += (s, e) => {
   BusyIndicatorVisibility = Visibility.Collapsed;  
   // Enable here the UI
   // You can get the login-result via the e.Result. Make sure to check also the e.Error for errors that happended during the login-operation
};
bgWorker.RunWorkerAsync();
Run Code Online (Sandbox Code Playgroud)

仅用于完整性:可以在登录发生之前为UI提供刷新时间.这是通过调度员完成的.然而,这是一个黑客攻击,IMO永远不应该被使用.但是如果您对此感兴趣,可以在StackOverflow中搜索wpf doevents.