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 }

以上只是一種實現方式,希望給有需要的人提供幫助。

效果如下:

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM