如何强制显示忙碌指示器? (WPF) [英] How can I force my busy indicator to display? (WPF)
问题描述
我创建了一个忙碌指示器-基本上是徽标旋转的动画.我已将其添加到登录窗口,并将Visibility属性绑定到我的视图模型的BusyIndicatorVisibility属性.
I've created a busy indicator - basically an animation of a logo spinning. I've added it to a login window and bound the Visibility property to my viewmodel's BusyIndicatorVisibility property.
当我单击登录时,我希望微调框出现在登录发生时(它调用Web服务以确定登录凭据是否正确).但是,当我将可见性设置为visible,然后继续登录时,直到完成登录后,微调框才会出现.在Winforms老式编码中,我将添加一个Application.DoEvents.如何使微调框出现在MVVM应用程序的WPF中?
When I click login, I want the spinner to appear whilst the login happens (it calls a web service to determine whether the login credentials are correct). However, when I set the visibility to visible, then continue with the login, the spinner doesn't appear until the login is complete. In Winforms old fashioned coding I would have added an Application.DoEvents. How can I make the spinner appear in WPF in an MVVM application?
代码是:
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 来执行此操作.像这样:
You have to make your login async. You can use the BackgroundWorker to do this. Something like:
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 .
Only for completness: There is the possibility to give the UI the time to refresh before the login takes place. This is done over the dispatcher. However this is a hack and IMO never should be used. But if you're interested in this, you can search StackOverflow for wpf doevents.
这篇关于如何强制显示忙碌指示器? (WPF)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!