• 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 }

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

    效果如下:

  • 相关阅读:
    javascript语法之函数案例练习
    javascript语法之函数的定义
    javascript语法之with语句
    javascript语法之for-in语句
    javascript语法之循环语句小练习
    centos 7 配置samba mount
    Centos 7 systemd.service — Service unit configuration
    Linux 下使用 ffmpeg 大批量合并 ts 文件, mp4切割文件为m3u8
    Debian 系统修改网卡ens33名称为 eth0
    star_namelist
  • 原文地址:https://www.cnblogs.com/hglSV/p/10686958.html
Copyright © 2020-2023  润新知