我创建了一个忙碌指示器-基本上是徽标旋转的动画。我已将其添加到登录窗口,并将Visibility属性绑定到我的视图模型的BusyIndi​​catorVisibility属性。

当我单击登录时,我希望微调框出现在登录发生时(它调用Web服务以确定登录凭据是否正确)。但是,当我将可见性设置为visible,然后继续登录时,直到完成登录后,微调框才会出现。在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;
        }

最佳答案

您必须使登录异步。您可以使用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。

07-24 20:03