设为首页 加入收藏

TOP

WPF 通过线程使用ProcessBar
2019-09-17 19:07:46 】 浏览:32
Tags:WPF 通过 线程 使用 ProcessBar

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

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

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Threading;
 6 using System.Threading.Tasks;
 7 using System.Windows;
 8 using System.Windows.Controls;
 9 using System.Windows.Data;
10 using System.Windows.Documents;
11 using System.Windows.Input;
12 using System.Windows.Media;
13 using System.Windows.Media.Imaging;
14 using System.Windows.Navigation;
15 using System.Windows.Shapes;
16 
17 namespace WpfTestProcessBar
18 {
19     /// <summary>
20     /// MainWindow.xaml 的交互逻辑
21     /// </summary>
22     public partial class MainWindow : Window
23     {
24         public delegate void ProgressDelegate(int percent);
25         public MainWindow()
26         {
27             InitializeComponent();
28             ProgressEvent += MainWindow_ProgressEvent;
29             beginImport();
30         }
31         void MainWindow_ProgressEvent(int percent)
32         {
33             Dispatcher.Invoke(new Action<System.Windows.DependencyProperty, object>(Pro.SetValue), System.Windows.Threading.DispatcherPriority.Background, new object[] { ProgressBar.ValueProperty, Convert.ToDouble(percent+ 1) });
34             Dispatcher.Invoke(new Action<System.Windows.DependencyProperty, object>(label.SetValue), System.Windows.Threading.DispatcherPriority.Background, new object[] { Label.ContentProperty, Convert.ToString((percent + 1)+"%") }); 
35 
36         }
37         private event ProgressDelegate ProgressEvent;
38         private void beginImport()
39         {
40             Pro.Maximum = 100;
41             Pro.Value = 0;
42             label.Content = "0%";
43             ThreadPool.QueueUserWorkItem(state =>
44             {
45                 Thread.Sleep(2000);
46                 for (int i = 0; i < 100; i++)
47                 {
48                     if (ProgressEvent != null)
49                     {
50                         ProgressEvent(i);
51                     }
52                     Thread.Sleep(10);
53                 }
54             });
55         }
56     }
57 }

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

效果如下:

 

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇DSAPI 3张图片实现花开动画 下一篇C#单例类的实现

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目