zoukankan      html  css  js  c++  java
  • 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 }

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

    效果如下:

  • 相关阅读:
    【3】jQuery学习——入门jQuery选择器之基本选择器
    对于转载引发的问题没见过这样强硬的论坛
    SQL2进制问题
    用SQL只获取日期的方法
    C#算法求2进制的问题
    ASP.NET Ajax In Action!读书笔记1
    Fckeditor配置
    MIME types list
    SQL case when then else end运用
    ASP.Net访问母版页(MasterPage)控件、属性、方法及母版页中调用内容页的方法
  • 原文地址:https://www.cnblogs.com/hglSV/p/10686958.html
Copyright © 2011-2022 走看看