前提非常简单-我有一个正在运行一些昂贵计算的类,我想展示一个ProgressBar来通知用户。由于我可能有很多计算周期,因此我希望有一个简单的ProgressBar表单,可以在我的代码中多次使用。该表单不需要知道其他任何内容,但是它的标题,ProgressBar的最大值以及何时执行步进和递增操作。更新调用是从“其他类”完成的,表单仅显示该更新。
以下代码来自实现目标的ProgressBar的Windows窗体版本(导出为dll)。我正在尝试使用WPF重新创建相同的功能。从到目前为止的研究来看,这是无法完成的。如果有人可以证明我是错误的,并且为后面的WPF代码和“其他类”中的方法演示了一个伪代码,我将非常高兴。
public partial class ProgressForm : Form {
private bool abortFlag;
string _format;
/// <summary>
/// Set up progress bar form and immediately display it modelessly.
/// </summary>
/// <param name="caption">Form caption</param>
/// <param name="format">Progress message string</param>
/// <param name="max">Number of elements to process</param>
public ProgressForm( string caption, string format, int max )
{
_format = format;
InitializeComponent();
Text = caption;
label1.Text = (null == format) ? caption : string.Format( format, 0 );
progressBar1.Minimum = 0;
progressBar1.Maximum = max;
progressBar1.Value = 0;
Show();
Application.DoEvents();
}
public void Increment()
{
++progressBar1.Value;
if( null != _format )
{
label1.Text = string.Format( _format, progressBar1.Value );
}
Application.DoEvents();
}
public bool getAbortFlag()
{
return abortFlag;
}
private void button1_Click(object sender, EventArgs e)
{
button1.Text = "Aborting...";
abortFlag = true;
}
protected override bool ProcessDialogKey(Keys keyData)
{
if (Form.ModifierKeys == Keys.None && keyData == Keys.Escape)
{
button1.Text = "Aborting...";
abortFlag = true;
return true;
}
return base.ProcessDialogKey(keyData);
}
public void SetText(string text)
{
label1.Text = text;
System.Windows.Forms.Application.DoEvents();
}
public void SetProgressBarMinMax(int min, int max)
{
progressBar1.Minimum = min;
progressBar1.Maximum = max;
progressBar1.Value = 0;
}
public void IncrementProgressBar()
{
progressBar1.Value++;
System.Windows.Forms.Application.DoEvents();
}
public void HideProgressBar()
{
progressBar1.Visible = false;
System.Windows.Forms.Application.DoEvents();
}
public void ShowProgressBar()
{
progressBar1.Visible = true;
System.Windows.Forms.Application.DoEvents();
}
}
public class OtherClass(){
int counter = 0;
int n = numberOfIterations;
string s = "{0} of " + n.ToString() + String.Format(" elements processed.", counter.ToString());
string caption = "Duplicating ..";
using (ProgressForm pf = new ProgressForm(caption, s, n)){
//Something heavy to compute
foreach (var sheet in sheetsToDuplicate)
{
if (pf.getAbortFlag())
{
return;
}
counter ++;
pf.Increment();
}
}
}
我认为这应该很简单,但是我无法找到一个单一的来源来展示如何实现这一目标。对我而言,重要的要点是:
谢谢。