【问题标题】:ProgressBar with BackgroundWorker in WPFWPF 中带有 BackgroundWorker 的 ProgressBar
【发布时间】:2014-04-04 03:16:02
【问题描述】:

我有一个 WPF 应用程序,该应用程序中的一项任务是打印一份 Telerik 报告,这需要一些时间。

我已经通过使用 BackgroundWorker 解决了屏幕冻结问题,但我想在 ProgressBar 中显示打印过程,我已经阅读了一些示例,但所有示例都在谈论 FOR 循环并将整数传递给 ProgressBar,但不能使用我的情况。

如果可能,我该怎么做?

这是我的 BackgroundWorker DoWork:

 void _printWorker_DoWork(object sender, DoWorkEventArgs e)
    {
        _receiptReport = new Receipt(_invoice.InvoiceID, _invoice.ItemsinInvoice.Count);
        printerSettings = new System.Drawing.Printing.PrinterSettings();
        standardPrintController = new System.Drawing.Printing.StandardPrintController();
        reportProcessor = new Telerik.Reporting.Processing.ReportProcessor();
        reportProcessor.PrintController = standardPrintController;
        instanceReportSource = new Telerik.Reporting.InstanceReportSource();
        instanceReportSource.ReportDocument = _receiptReport;
        reportProcessor.PrintReport(instanceReportSource, printerSettings);
    }

提前致谢

【问题讨论】:

  • 如果你不传递一个设置进度百分比的 int,ProgressBar 将如何显示进度?
  • 我的问题是如何在我的情况下传递 int ??

标签: c# wpf backgroundworker


【解决方案1】:

当您定义您的BackgroundWorker 时,启用报告进度:

worker.WorkerReportsProgress = true;
worker.ProgressChanged += _printWorker_ProgressChanged;

ProgressBar 添加到您的窗口。将Maximum 设置为您想要报告的任何“更新”:

<ProgressBar x:Name="ProgressBar1" Maximum="8" />

然后在DoWork事件中的每一行代码之后,通过BackgroundWorker.ReportProgress方法增加ProgressBarValue

void _printWorker_DoWork(object sender, DoWorkEventArgs e)
{
    var worker = (BackgroundWorker)sender;

    worker.ReportProgress(0);
    _receiptReport = new Receipt(_invoice.InvoiceID, _invoice.ItemsinInvoice.Count);
    worker.ReportProgress(1);
    printerSettings = new System.Drawing.Printing.PrinterSettings();
    ...
    ...
    worker.ReportProgress(6);
    instanceReportSource.ReportDocument = _receiptReport;
    worker.ReportProgress(7);
    reportProcessor.PrintReport(instanceReportSource, printerSettings);
    worker.ReportProgress(8);
}

private void _printWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
    ProgressBar1.Value = e.ProgressPercentage;
}

您还需要在调用RunWorkerAsync() 之前使ProgressBar 可见,然后将其隐藏在RunWorkerCompleted 事件中。

【讨论】:

  • 谢谢,这就是我要找的:)
【解决方案2】:

您必须为后台工作人员的 ProgressChanged 事件提供事件处理程序。但是,您需要将一些数字传递给该事件以指示完成百分比,否则它对于更新进度条不是很有用。

我的建议是只制作一个动画 gif 或其他东西来向用户表明应用程序当前正在运行。

【讨论】:

  • 感谢@Chris 抽出宝贵时间,我认为您的建议是做我想做的事的好方法,我会试试的'
  • 或者您可以将 ProgessBar.IsIndeterminate 设置为 true。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-05
相关资源
最近更新 更多