我在ViewModel中有一个后台工作程序。当执行按钮的命令时,我想在新线程中启动该过程。这是我的示例代码
private void ShowValidations(object obj)
{
progress = "Please Wait....";
var worker = new BackgroundWorker();
worker.WorkerReportsProgress = true;
worker.DoWork += worker_DoWork;
worker.ProgressChanged += worker_ProgressChanged;
worker.RunWorkerCompleted += worker_RunWorkerCompleted;
}
在我的工作方法中
private void worker_DoWork(object sender, DoWorkEventArgs e)
{
var worker = sender as BackgroundWorker;
DoValidation();
for(int i=0;i<100;i++)
{
worker.ReportProgress(i); //Not sure here what should be written in the Background Worker Report progress event.
}
}
private void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
ViewSource.Source = _validationResults;
ViewSource.View.Refresh();
progress = "Validations Complete";
Isindeterminate = false;
//prvalue = 99;
}
DoValidation是一种方法,可以像三层架构一样为其他类提取结果。
private void DoValidation()
{
try
{
if (!string.IsNullOrEmpty(_selectedEntity))
{
var jobEngine = new JobEngine();
var jobId = JobEntities[0].JobId;
jobEngine.ProcessValidation(_selectedEntity, jobId); //Get results from other class.
_validationResults = _validations.ValidationSummary(_selectedEntity, jobId); //_validationResults is an Observable Collection.
}
else
{
MessageBox.Show("Please select an Entity to validate");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message + "Sorry we are having problems with " + _selectedEntity);
}
}
如何根据已完成的工作更新UI上的进度条。后台工作者的ProgressChanged事件应该是什么..这是我的查看代码。
<ProgressBar HorizontalAlignment="Left" Minimum="1" Maximum="99" Height="20" Margin="424,24,0,0" Grid.Row="1" Value="{Binding prvalue,Mode=OneWay}" VerticalAlignment="Top" Width="194"/>
<Label x:Name="LblprogressLabel" FontSize="14" Content="{Binding prvalue,Mode=OneWay}" HorizontalAlignment="Center" Margin="507,18,339,23" Grid.Row="1" Width="26"/>
<Label Content="{Binding progress,Mode=OneWay}" FontSize="16" FontWeight="Bold" HorizontalAlignment="Left" Margin="623,20,0,0" Grid.Row="1" VerticalAlignment="Top" Width="227" Height="34"/>
请不要担心datacontext一切都很好。我不能写每个类的整个代码,因为它是如此巨大。 请帮助!!!!