2

我正在尝试将百分比值放入我的进度条,但它看起来像眨眼然后消失。

这是我的ProgressChanged活动:

C# 代码

public void button1_click(object sender, EventArgs e)
{
BackgroundWorker _worker = new BackgroundWorker();
                _worker.WorkerReportsProgress = true;
                _worker.ProgressChanged += new ProgressChangedEventHandler(_worker_ProgressChanged);
                _worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(_worker_RunWorkerCompleted);                
                _worker.DoWork += (s, e2) =>
                {
                    for (int i = 0; i <= xmlnode.Count - 1; i++)
                    {
                         _worker.ReportProgress((int)100 * i / (xmlnode.Count - 1));
                         // Many validations here
                    }
                 }
}

void _worker_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {            
            progressBar1.Value = e.ProgressPercentage;            

             // Here I tryied to put the percentage value in progress bar

            int percent = (int)(((double)progressBar1.Value / (double)progressBar1.Maximum) * 100);
            progressBar1.CreateGraphics().DrawString(percent.ToString() + "%", new Font("Arial", (float)8.25, FontStyle.Regular), Brushes.Black, new PointF(progressBar1.Width / 2 - 10, progressBar1.Height / 2 - 7));
        }
4

2 回答 2

0

文本只是闪烁,因为它没有在 上重绘Paint。消耗Paint进度条的事件并在那里绘制百分比。您只需将其存储在类变量中即可轻松获取该百分比。

于 2013-07-08T12:02:09.807 回答
0

进度条是一个动画控件。当您更改其百分比时,它会使其绘制表面无效并完全重新绘制它。这意味着您的百分比是为一帧绘制的,然后随着动画的播放而消失。

要解决此问题,您必须创建一个从 Control 或 Progress bar 继承的新控件,并将您的代码添加到处理百分比写入的 OnPaint 事件。通过在 OnPaint 中,每次控件重新绘制自身时都会执行它,而不仅仅是一次。或者,只需将委托挂钩到现有进度条的现有 Paint 事件,这可能更容易。

这看起来像:

//Somewhere during initialisation, this is called once only
progressBar1.Paint+= new PaintEventHandler((object sender, PaintEventArgs e) => 
e.Graphics.DrawString(progressBar1.Value.ToString() + "%", new Font("Arial", (float)8.25, FontStyle.Regular), Brushes.Black, new PointF(progressBar1.Width / 2 - 10, progressBar1.Height / 2 - 7)));
于 2013-07-08T12:03:12.840 回答