我正在我的Windows应用程序中实现进度条控件。 这是我的进度条形码的样子。
public partial class ProgressBar : UserControl
{
public event Action OnCommand;
private int _progressInitial = 0;
private int _progressMaximum = 100;
#region :: Member Methods ::
//------------------------------------------------------------------------------
public void Start()
{
_timer.Start();
_progressBar.Value = 0;
if (!_backWorker.IsBusy)
{
_lblProgressText.Text = string.Empty;
_backWorker.RunWorkerAsync();
}
}
//------------------------------------------------------------------------------
public void End()
{
if (_backWorker.WorkerSupportsCancellation)
{
_timer.Stop();
_backWorker.CancelAsync();
}
}
//------------------------------------------------------------------------------
#endregion
public ProgressBar()
{
InitializeComponent();
_progressBar.Maximum = _progressMaximum;
_backWorker.WorkerSupportsCancellation = true;
_backWorker.WorkerReportsProgress = true;
}
//------------------------------------------------------------------------------
private void _backWorker_DoWork(object sender, DoWorkEventArgs e)
{
if (this.OnCommand != null)
this.Invoke((Action)(() => OnCommand()));
if (_backWorker.CancellationPending)
e.Cancel = true;
}
//------------------------------------------------------------------------------
private void _backWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
_lblProgressText.Text = string.Format("{0}%", e.ProgressPercentage);
_progressBar.Value = e.ProgressPercentage;
}
//------------------------------------------------------------------------------
private void _backWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
_progressBar.Value = _progressMaximum;
_lblProgressText.Text = string.Format("{0}%", _progressMaximum);
_timer.Stop();
_timer.Enabled = false;
}
//------------------------------------------------------------------------------
private void _timer_Tick(object sender, EventArgs e)
{
if (_backWorker.IsBusy)
{
_progressInitial += 10;
if (_progressInitial >= _progressMaximum)
_progressInitial = 99;
_backWorker.ReportProgress(_progressInitial);
}
}
//------------------------------------------------------------------------------
}
public partial class Sample : UserControl
{
public Sample()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
progressBar1.Start();
}
private void button2_Click(object sender, EventArgs e)
{
progressBar1.End();
}
private void progressBar1_Command()
{
System.Threading.Thread.Sleep(5000);
}
}
这是UserControl
,在我的DoWork
后台工作程序中,我对父控件执行长数据库操作,该操作会触发OnCommand
事件操作。
这个OnCommand
处理程序将包含长数据库操作,这就是我使用计时器更新进度条一定时间间隔的原因。
如果我直接在Form
上使用控件,这可以正常工作但是如果我在usercontrol包含的另一个UserControl
中使用此控件
OnCommand方法执行的那一刻,计时器停止滴答。
为什么它适用于表单而不是UserControl
?
提前致谢
此致 Francis P。