欢迎来到代码驿站!

.NET代码

当前位置:首页 > 软件编程 > .NET代码

WPF通过线程使用ProcessBar的方法详解

时间:2021-07-18 08:24:44|栏目:.NET代码|点击:

前言

WPF下使用进度条也是非常方便的,如果直接采用循环然后给ProcessBar赋值,理论上是没有问题的,不过这样会卡主主UI线程,我们看到的效果等全部都结束循环后才出现最后的值。

所以需要采用线程或者后台方式给进度条赋值的方式,以下通过线程来触发事件触发的方式来实现给进度条赋值。这样就可以模拟我们在实际过程中处理数据的一种进度方式。

方法示例:

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);
    }
   });
  }
 }
}

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

效果如下:

总结

上一篇:使用C#实现在屏幕上画图效果的代码实例

栏    目:.NET代码

下一篇:C#学习教程之Socket的简单使用

本文标题:WPF通过线程使用ProcessBar的方法详解

本文地址:http://www.codeinn.net/misctech/158596.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有