如何在C#中使用进度条 [英] How to use progress bar in C#
问题描述
我有一个Windows窗体应用程序项目。
我有一个提交按钮。在它的方法中有一个很长的代码。
我希望当我点击提交按钮时,进度条应该在按钮方法中的代码完全完成时开始和结束。
我尝试了什么:
i尝试使用计时器并在按钮的星形启动计时器方法
并在timer_click方法中将进度条增加1。
但是进度条卡在起始位置。
i尝试过背景工作但不能使用它。
任何人都可以帮我轻松解决这个问题吗?不使用线程和所有
I have a windows form application project with me.
I have a submit button in it. And in its method there is a long code.
I want that when i click on the submit button the progress bar should start and end when the code in the button's method is completed completely.
What I have tried:
i tried using timer and started timer in star of button's method
and incremented progress bar by 1 in timer_click method.
but the progress bar is stuck in the starting.
i tried backgroundworker but couldn't use it.
can anyone help me achive this easily? without use of threading and all
推荐答案
我在使用WPF时也遇到过这个问题,你可能需要这样的东西:
I experienced this problem too when starting with WPF, you probably need something like this:
progressbar1.Dispatcher.Invoke(() => progressbar1.Value = i, DispatcherPriority.Background);
参见: c# - 实时更新进度条wpf - 堆栈溢出 [ ^ ]
请看一下这个例子:
MainWindow .xaml
Please have a look at this example:
MainWindow.xaml
<Window x:Class="WpfApplication3.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525">
<Grid>
<ProgressBar Name="ProgressBar" Height="20"></ProgressBar>
</Grid>
</Window>
MainWindow.xaml.cs
MainWindow.xaml.cs
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
namespace WpfApplication3
{
public partial class MainWindow
{
public MainWindow()
{
InitializeComponent();
ProgressBar.Minimum = 0;
ProgressBar.Maximum = 100;
ProgressBar.Value = 0;
DoIt();
}
public void DoIt()
{
var task = new Task(() =>
{
for (var i = 0; i <= 100; i++)
{
SetProgressBarValue(i);
// Simulate some work...
Thread.Sleep(100);
}
});
task.Start();
}
public void SetProgressBarValue(int value)
{
Application.Current.Dispatcher.Invoke(() =>
{
ProgressBar.Value = value;
});
}
}
}
这篇关于如何在C#中使用进度条的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!