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> 22public partial class MainWindow : Window 23{ 24public delegate void ProgressDelegate(int percent); 25public MainWindow() 26{ 27InitializeComponent(); 28ProgressEvent += MainWindow_ProgressEvent; 29beginImport(); 30} 31void MainWindow_ProgressEvent(int percent) 32{ 33Dispatcher.Invoke(new Action<System.Windows.DependencyProperty, object>(Pro.SetValue), System.Windows.Threading.DispatcherPriority.Background, new object[] { ProgressBar.ValueProperty, Convert.ToDouble(percent+ 1) }); 34Dispatcher.Invoke(new Action<System.Windows.DependencyProperty, object>(label.SetValue), System.Windows.Threading.DispatcherPriority.Background, new object[] { Label.ContentProperty, Convert.ToString((percent + 1)+"%") }); 35 36} 37private event ProgressDelegate ProgressEvent; 38private void beginImport() 39{ 40Pro.Maximum = 100; 41Pro.Value = 0; 42label.Content = "0%"; 43ThreadPool.QueueUserWorkItem(state => 44{ 45Thread.Sleep(2000); 46for (int i = 0; i < 100; i++) 47{ 48if (ProgressEvent != null) 49{ 50ProgressEvent(i); 51} 52Thread.Sleep(10); 53} 54}); 55} 56} 57 }
以上只是一種實現方式,希望給有需要的人提供幫助。
效果如下: