C#-进度条不会显示值
本文关键字:显示 C#- | 更新日期: 2023-09-27 18:21:24
在我的应用程序中,我需要一个进度条来显示植物生长的进度。这将是代码:
private static Timer farmProgress;
internal void initFarmProgTimer( int step, int max = 100 )
{
farmProgress = new Timer();
farmProgress.Tick += new EventHandler(farmProgress_Tick);
farmProgress.Interval = step; // in miliseconds
farmProgress.Start();
}
private void farmProgress_Tick(object sender, EventArgs e)
{
if (increment >= 100)
{
// wait till user get plant
}
else
{
increment++;
plantProgressBar.Value = increment;
}
}
这里调用initFarmProgTimer
函数:
public static System.Threading.Timer growTimer;
public static void InitGrowTimer(int time, string name)
{
growTimer = new System.Threading.Timer(growTimer_Finished, null, time, Timeout.Infinite);
plantActive = true;
Menu menu = new Menu();
menu.initFarmProgTimer(time / 100);
}
请注意,从中调用此函数的类不是窗体,但定义函数的类是窗体。
有人知道我的错误是什么吗?
编辑这是对InitGrowtTimer函数的调用
switch ( index )
{
case 0:
currentPlant = wheat.name;
plantQ = printPlantDatas("wheat");
if (plantQ == true)
{
InitGrowTimer(wheat.time, wheat.name);
wheat.planted++;
}
break;
}
您正在将值设置为进度条,它只会将进度设置为当前值。你必须增加它。我已经为你添加了加号(+)
private void farmProgress_Tick(object sender, EventArgs e)
{
if (increment >= 100)
{
// wait till user get plant
}
else
{
increment++;
plantProgressBar.Value += increment;
}
}
我不清楚什么在Form上,什么没有,但假设它在Form上:
private void farmProgress_Tick(object sender, EventArgs e)
{
if (increment >= 100)
{
// wait till user get plant
}
else
{
increment++;
plantProgressBar.Value = increment;
}
}
将其更改为这样,以便从UI线程更新控件:
private void farmProgress_Tick(object sender, EventArgs e)
{
if (increment >= 100)
{
// wait till user get plant
}
else
{
increment++;
this.Invoke(new Action(() => {
plantProgressBar.Value = increment;
}));
}
}
更新
我的答案是错误的,我没想到会这样,但我创建了一个Forms应用程序,这很好地增加了进度条:
public partial class Form1 : Form
{
private Timer farmProgress;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
farmProgress = new Timer();
farmProgress.Tick += farmProgress_Tick;
farmProgress.Interval = 1000; // in miliseconds
farmProgress.Start();
}
void farmProgress_Tick(object sender, EventArgs e)
{
progressBar1.Value++;
}
}