欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

WPF通过线程使用ProcessBar的方法详解

程序员文章站 2023-11-10 08:32:46
前言 wpf下使用进度条也是非常方便的,如果直接采用循环然后给processbar赋值,理论上是没有问题的,不过这样会卡主主ui线程,我们看到的效果等全部都结束循环后才出...

前言

wpf下使用进度条也是非常方便的,如果直接采用循环然后给processbar赋值,理论上是没有问题的,不过这样会卡主主ui线程,我们看到的效果等全部都结束循环后才出现最后的值。

所以需要采用线程或者后台方式给进度条赋值的方式,以下通过线程来触发事件触发的方式来实现给进度条赋值。这样就可以模拟我们在实际过程中处理数据的一种进度方式。

方法示例:

using system;
using system.collections.generic;
using system.linq;
using system.text;
using system.threading;
using system.threading.tasks;
using system.windows;
using system.windows.controls;
using system.windows.data;
using system.windows.documents;
using system.windows.input;
using system.windows.media;
using system.windows.media.imaging;
using system.windows.navigation;
using system.windows.shapes;

namespace wpftestprocessbar
{
 /// <summary>
 /// mainwindow.xaml 的交互逻辑
 /// </summary>
 public partial class mainwindow : window
 {
  public delegate void progressdelegate(int percent);
  public mainwindow()
  {
   initializecomponent();
   progressevent += mainwindow_progressevent;
   beginimport();
  }
  void mainwindow_progressevent(int percent)
  {
   dispatcher.invoke(new action<system.windows.dependencyproperty, object>(pro.setvalue), system.windows.threading.dispatcherpriority.background, new object[] { progressbar.valueproperty, convert.todouble(percent+ 1) });
   dispatcher.invoke(new action<system.windows.dependencyproperty, object>(label.setvalue), system.windows.threading.dispatcherpriority.background, new object[] { label.contentproperty, convert.tostring((percent + 1)+"%") }); 

  }
  private event progressdelegate progressevent;
  private void beginimport()
  {
   pro.maximum = 100;
   pro.value = 0;
   label.content = "0%";
   threadpool.queueuserworkitem(state =>
   {
    thread.sleep(2000);
    for (int i = 0; i < 100; i++)
    {
     if (progressevent != null)
     {
      progressevent(i);
     }
     thread.sleep(10);
    }
   });
  }
 }
}

以上只是一种实现方式,希望给有需要的人提供帮助。

效果如下:

WPF通过线程使用ProcessBar的方法详解

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对的支持。