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

时间:2010-09-16 09:18:45

标签: 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;
        }

3 个答案:

答案 0 :(得分: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();

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

答案 1 :(得分:2)

您可以尝试在单独的主题中运行繁忙的标记,如本文所述:Creating a Busy Indicator in a separate thread in WPF

或尝试运行new BusyIndicator from the Extended WPF Toolkit

但是如果你不把逻辑放在后台线程中,我很确定你会不幸。

答案 2 :(得分:0)

您的登录代码是否在UI线程上运行?这可能会阻止数据绑定更新。