WPF通過線程使用ProcessBar的方法詳解
前言
WPF下使用進(jìn)度條也是非常方便的,如果直接采用循環(huán)然后給ProcessBar賦值,理論上是沒有問題的,不過這樣會卡主主UI線程,我們看到的效果等全部都結(jié)束循環(huán)后才出現(xiàn)最后的值。
所以需要采用線程或者后臺方式給進(jìn)度條賦值的方式,以下通過線程來觸發(fā)事件觸發(fā)的方式來實(shí)現(xiàn)給進(jìn)度條賦值。這樣就可以模擬我們在實(shí)際過程中處理數(shù)據(jù)的一種進(jìn)度方式。
方法示例:
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); } }); } } }
以上只是一種實(shí)現(xiàn)方式,希望給有需要的人提供幫助。
效果如下:
總結(jié)
以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,謝謝大家對腳本之家的支持。
相關(guān)文章
C#高效比較兩個(gè)DataTable數(shù)據(jù)差異化的方法實(shí)現(xiàn)
本文主要介紹了C#高效比較兩個(gè)DataTable數(shù)據(jù)差異化的方法實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2022-05-05c# 實(shí)現(xiàn)語音聊天的實(shí)戰(zhàn)示例
這篇文章主要介紹了c# 實(shí)現(xiàn)語音聊天的實(shí)戰(zhàn)示例,幫助大家更好的理解和學(xué)習(xí)使用c#,感興趣的朋友可以了解下2021-02-02關(guān)于finalize機(jī)制和引用、引用隊(duì)列的用法詳解
下面小編就為大家?guī)硪黄P(guān)于finalize機(jī)制和引用、引用隊(duì)列的用法詳解。小編覺得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2016-09-09利用WCF雙工模式實(shí)現(xiàn)即時(shí)通訊
這篇文章主要介紹了利用WCF雙工模式實(shí)現(xiàn)即時(shí)通訊的相關(guān)資料,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2016-09-09