我应该如何在应用程序在后台繁忙时显示消息框或其他类似通知,类似于这个模型:
。
![enter image description here](https://istack.dev59.com/TuVtD.webp)
WPF Extended Toolkit 中有一个繁忙指示器,我经常使用它:
该工具包可以通过NuGet方便地添加到您的项目中作为引用。 我个人在近期的所有WPF项目中都使用了它(以及该工具包中的许多其他有用控件)。
要使用它,请在XAML代码中将您的控件与繁忙指示器一起包围:
<extToolkit:BusyIndicator ...>
<Grid>
<Button Content="Click to do stuff" />
<!-- your other stuff here -->
</Grid>
</extToolkit:BusyIndicator>
当你想要弹出窗口时,只需将IsBusy
属性设置为true
,并在应该隐藏时设置为false。在适当的MVVM架构中,通常会将属性在XAML中数据绑定到视图模型中的属性,然后相应地设置为true/false:
<extToolkit:BusyIndicator IsBusy="{Binding IsBusy}" >
但如果你没有使用MVVM,你可以在代码中手动设置它,通常在按钮单击处理程序中:
给控件命名以便在代码中引用:
<extToolkit:BusyIndicator x:Name="busyIndicator" >
void myButton_Click(object sender, RoutedEventArgs e)
{
busyIndicator.IsBusy = true;
// Start your background work - this has to be done on a separate thread,
// for example by using a BackgroundWorker
var worker = new BackgroundWorker();
worker.DoWork += (s,ev) => DoSomeWork();
worker.RunWorkerCompleted += (s,ev) => busyIndicator.IsBusy = false;
worker.RunWorkerAsync();
}
public bool IsBusy {get {return _isBusy;} set{_isBusy=value;OnPropertyChanged("IsBusy");}}
private bool _isBusy;
2.) 在您的命令中添加两个事件“Started”和“Completed”
public event Action Completed;
public event Action Started;
3.) 在您的ViewModel中订阅这些事件并设置繁忙状态。
LoadImagesCommand.Started += delegate { IsBusy = true; };
LoadImagesCommand.Completed += delegate { IsBusy = false; };
4.) 在您的窗口中,现在可以绑定到该状态。
<Popup Visibility="{Binding Path=IsBusy,Converter={StaticResource boolToVisibilityConverter}}"/>
5.) 将以下内容添加到任何已加载的资源字典中:
<BooleanToVisibilityConverter x:Key="boolToVisibilityConverter"/>
就是这样了!您可以填充您想要的生活到弹出窗口中...
Messagebox.Show()
。 - Isak Savo