我创建了一个小工具,用于将数据从一个数据库导入和转换到另一个数据库。由于这需要花费大量时间,因此我想为具有不确定进度条的用户显示某种进度。 只要导入正在运行,进度条也应该运行。 我使用这个网站作为参考:The ProgressBar control但我无法理解DoWork-Method的作用,因为不确定进度条的选项设置了一次。
我提出了一个中途运行的解决方案,在导入完成后我无法停止动画。 有人可以帮助我吗?
XAML:
<ProgressBar Minimum="{Binding Path=Minimum}" Maximum="100" IsIndeterminate="{Binding Path=IsIndeterminate}" Height="20" Grid.Column="2" Grid.Row="5" Grid.ColumnSpan="2"/>
视图模型:
public void StartImportThread()
{
ButtonsEnabled = false;
var th = new Thread(new ThreadStart(StartImport));
th.IsBackground = true;
th.Start();
}
public void StartImport()
{
_threadDispatcher = Dispatcher.CurrentDispatcher;
BackgroundWorker worker = new BackgroundWorker();
worker.WorkerReportsProgress = true;
worker.WorkerSupportsCancellation = true;
worker.DoWork += worker_DoWork;
worker.RunWorkerCompleted += worker_Complete;
worker.RunWorkerAsync();
// Doing Import Stuff
worker.CancelAsync(); // Import finished
ButtonsEnabled=true;
}
void worker_DoWork(object sender, DoWorkEventArgs e)
{
// while(true)
// {
Minimum = 0;
IsIndeterminate = true;
// }
}
private void worker_Complete(object sender, RunWorkerCompletedEventArgs e)
{
// if (e.Cancelled)
// {
IsIndeterminate = false;
Minimum = 100;
// }
}
答案 0 :(得分:1)
这对我有用。 RelayCommand和ViewModelBase来自MvvmLight库,DoWorkCommand由一个按钮调用:
<Button Name="BtnReload" Command="{Binding DoWorkCommand}" Width="75" Height="25"/>
<ProgressBar Minimum="{Binding Path=Minimum}" Maximum="100" IsIndeterminate="{Binding Path=IsIndeterminate}" Height="20"/>
public class MainViewModel : ViewModelBase {
private RelayCommand _doWorkCommand;
private bool _isIndeterminate;
private int _minimum;
private Dispatcher _threadDispatcher;
public int Minimum {
get { return _minimum; }
set {
_minimum = value;
RaisePropertyChanged(nameof(Minimum));
}
}
public bool IsIndeterminate {
get { return _isIndeterminate; }
set {
_isIndeterminate = value;
RaisePropertyChanged(nameof(IsIndeterminate));
}
}
public MainViewModel(IDataService dataService) {
}
public void StartImportThread() {
// ButtonsEnabled = false;
var th = new Thread(new ThreadStart(StartImport));
th.IsBackground = true;
th.Start();
}
public void StartImport() {
_threadDispatcher = Dispatcher.CurrentDispatcher;
BackgroundWorker worker = new BackgroundWorker();
worker.WorkerReportsProgress = true;
worker.WorkerSupportsCancellation = true;
worker.DoWork += worker_DoWork;
worker.RunWorkerCompleted += worker_Complete;
worker.RunWorkerAsync();
// Doing Import Stuff
worker.CancelAsync(); // Import finished
// ButtonsEnabled = true;
}
void worker_DoWork(object sender, DoWorkEventArgs e) {
Minimum = 0;
IsIndeterminate = true;
//for (int i = 0; i < 30; i++) {
// Thread.Sleep(100);
//}
}
void worker_Complete(object sender, RunWorkerCompletedEventArgs e) {
IsIndeterminate = false;
Minimum = 100;
}
public RelayCommand DoWorkCommand => _doWorkCommand ??
(_doWorkCommand = new RelayCommand(() => StartImportThread()));
}