WPF通过线程使用ProcessBar的方法详解
前言
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); } }); } } }
以上只是一种实现方式,希望给有需要的人提供帮助。
效果如下:
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对我们的支持。
栏 目:C#教程
本文地址:https://www.xiuzhanwang.com/a1/C_jiaocheng/4793.html
您可能感兴趣的文章
- 01-10C#通过反射获取当前工程中所有窗体并打开的方法
- 01-10C#停止线程的方法
- 01-10C#通过重写Panel改变边框颜色与宽度的方法
- 01-10C#实现多线程下载文件的方法
- 01-10C#实现多线程写入同一个文件的方法
- 01-10C#获取进程或线程相关信息的方法
- 01-10C#通过Semaphore类控制线程队列的方法
- 01-10C#线程队列用法实例分析
- 01-10C#及WPF获取本机所有字体和颜色的方法
- 01-10WPF实现类似360安全卫士界面的程序源码分享


阅读排行
本栏相关
- 01-10C#通过反射获取当前工程中所有窗体并
- 01-10关于ASP网页无法打开的解决方案
- 01-10WinForm限制窗体不能移到屏幕外的方法
- 01-10WinForm绘制圆角的方法
- 01-10C#实现txt定位指定行完整实例
- 01-10WinForm实现仿视频 器左下角滚动新
- 01-10C#停止线程的方法
- 01-10C#实现清空回收站的方法
- 01-10C#通过重写Panel改变边框颜色与宽度的
- 01-10C#实现读取注册表监控当前操作系统已
随机阅读
- 01-10SublimeText编译C开发环境设置
- 08-05DEDE织梦data目录下的sessions文件夹有什
- 01-10C#中split用法实例总结
- 01-11ajax实现页面的局部加载
- 08-05织梦dedecms什么时候用栏目交叉功能?
- 04-02jquery与jsp,用jquery
- 01-10delphi制作wav文件的方法
- 08-05dedecms(织梦)副栏目数量限制代码修改
- 01-11Mac OSX 打开原生自带读写NTFS功能(图文
- 01-10使用C语言求解扑克牌的顺子及n个骰子