【问题标题】:How to use the WPF progressbar?如何使用 WPF 进度条?
【发布时间】:2011-09-27 23:31:58
【问题描述】:

我正在尝试使用将 IsIndeterminate 属性设置为 true 的 WPF 进度条控件。 我的问题是它没有得到更新。

我正在做这样的事情:

pbProgressBar.Visibility = Visibility.Visible; 
//do time consuming stuff
pbProgressBar.Visibility = Visibility.Hidden;

我试图将它包装在一个线程中,然后使用 Dispatcher 对象调度它。 我应该如何解决这个问题:)。

【问题讨论】:

  • 没有更新是什么意思?如果将 IsIndeterminate 设置为 true,它只会显示连续的“进度”并忽略 value 属性,因此它永远不会真正更新,只会显示连续的进度。你是说它什么都不做?

标签: c# .net wpf


【解决方案1】:

您必须在后台线程上执行耗时的操作,并且您必须确保在后台线程完成其操作之前之后Visibility 设置回Hidden。基本流程如下:

private void _button_Click(object sender, RoutedEventArgs e)
{
   _progressBar.Visibility = Visibility.Visible;

   new Thread((ThreadStart) delegate
   {
       //do time-consuming work here

       //then dispatch back to the UI thread to update the progress bar
       Dispatcher.Invoke((ThreadStart) delegate
       {
           _progressBar.Visibility = Visibility.Hidden;
       });

   }).Start();
}

【讨论】:

  • 不,一旦退出就会被清理。这是在后台运行任务的多种方法之一。也可以看看 ThreadPool。
  • 实际上,如果您有这样的一次性任务,BackgroundWorker 更适合,因为它会免费为您提供 OnCompleted 通知,并且它会在 UI 线程上。同样在您的示例中,无需通过调用 Invoke 来阻塞工作线程,BeginInvoke 就可以了
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-07-29
相关资源
最近更新 更多