我正在尝试在程序中添加进度条。
FileLoadPB.Maximum = mainClass.values.realXPos.Count;
for (int i = 0; i < mainClass.values.realXPos.Count; ++i)
{
FileLoadPB.Value += i;
ComponentList.Items.Add(new MappedPoint { pointNum = i + 1, xPoint = mainClass.values.realXPos[i], yPoint = mainClass.values.realYPos[i] });
}
每次将对象添加到ListView时,我希望FileLoadPB进度条按“i”递增。这可行,但它实际上并没有显示栏的进展。它只在循环开始时显示为空,完整和结束。我已经在BackgroundWorker上阅读了一些内容,但是我不确定如何实现它。
答案 0 :(得分:0)
以下代码只是一个假人来说明如何使用BackgroundWorker。希望它有所帮助
public partial class MainWindow : Window {
BackgroundWorker backgroundWorker = new BackgroundWorker();
List<int> listDummy = new List<int>();
public MainWindow() {
InitializeComponent();
backgroundWorker.WorkerReportsProgress = true;
backgroundWorker.ProgressChanged += backgroundWorker_ProgressChanged;
backgroundWorker.DoWork += backgroundWorker_DoWork;
}
void backgroundWorker_DoWork(object sender, DoWorkEventArgs e) {
var numberOfItems = 111;
for (int i = 0; i < numberOfItems; i++) {
listDummy.Add(i);
Thread.Sleep(500);
backgroundWorker.ReportProgress(Convert.ToInt32((double)i / numberOfItems * 100));
}
}
void backgroundWorker_ProgressChanged(object sender, ProgressChangedEventArgs e) {
progressBar1.Value = e.ProgressPercentage;
}
private void Button_Click(object sender, RoutedEventArgs e) {
backgroundWorker.RunWorkerAsync();
}
}