这篇文章主要给大家介绍了关于WPF通过线程使用ProcessBar的相关资料,文中通过示例代码介绍的非常详细,对大家学习或者使用WPF具有一定的参考学习价值,需要的朋友们下面来一起学习学习吧
前言
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);
}
});
}
}
}
以上只是一种实现方式,希望给有需要的人提供帮助。
效果如下:
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对编程学习网的支持。
沃梦达教程
本文标题为:WPF通过线程使用ProcessBar的方法详解
猜你喜欢
- c# 模拟线性回归的示例 2023-03-14
- Oracle中for循环的使用方法 2023-07-04
- Unity Shader实现模糊效果 2023-04-27
- WPF使用DrawingContext实现绘制刻度条 2023-07-04
- user32.dll 函数说明小结 2022-12-26
- 如何使用C# 捕获进程输出 2023-03-10
- C# 使用Aspose.Cells 导出Excel的步骤及问题记录 2023-05-16
- 在C# 8中如何使用默认接口方法详解 2023-03-29
- Unity3D实现渐变颜色效果 2023-01-16
- .NET CORE DI 依赖注入 2023-09-27