我有一个BackgroundWorker,并在该工作人员,我正在从Excel文件中读取数据。 如果excel文件中有错误,工作人员完成,然后显示另一个表单,用户可以input更正,然后按OK键,然后从头开始再次运行工人。 当工作人员成功完成时,应该更新我的主窗口上的标签,说它已经加载了Excel。 但标签不会更新。 当我debugging它时,我可以看到更新标签运行的代码,但它根本不起作用。 请帮忙,这让我疯狂!
这是我的代码。
private void worker_ReadFileData(object sender, DoWorkEventArgs e) { for (int j = 1; j < rcount + 1; j++) { worker.ReportProgress(j); // Do work if (j == 1) { ColumnIndex column = this.ValidateColumnIndexes(tableType); if (column != null) { // If error in file, complete worker fileData.isDataLoaded = false; e.Result = fileData; return; } } } fileData.isDataLoaded = true; e.Result = fileData; // Pass the data to the completed method. } private void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { if (e.Error != null) { } else if (e.Cancelled) { } else { FileData fileData = (FileData) e.Result; if (fileData.isDataLoaded == true) { testLabel.Content = "It works!"; } else { // Show Dialog where user can input the correction ColumnIndexPrompt columnIndexPrompt = new ColumnIndexPrompt(fileData.FilePath, fileData.FileExtension, fileData.TableType, fileData.Column); columnIndexPrompt.ShowDialog(); } } } public void TriggerReadDataFile(string filePath, string fileExt, int tableType) { progBar.Value = 0; // Read the file data and populate the Registrars list, then show the datagrid worker.RunWorkerAsync(new FileData(filePath, fileExt, tableType)); }
编辑:这是从第二个窗口,我打开的代码(在上面的代码中使用.ShowDialog())
public ColumnIndexPrompt(string filePath, string fileExt, int tableType, ColumnIndex column) { InitializeComponent(); this.filePath = filePath; this.fileExt = fileExt; this.tableType = tableType; this.column = column; lblColumnIndexErrorMsg.Text = column.ErrorMsg; } private void btnColumnIndexApply_Click(object sender, RoutedEventArgs e) { MainWindow originalForm = new MainWindow(); int correctColumnNumber = int.Parse(txtColumnIndexCorrection.Text); column.Index = correctColumnNumber - 1; originalForm.UpdateSingleColumnIndex(column); originalForm.TriggerReadDataFile(this.filePath, this.fileExt, this.tableType); this.Close(); }
您正在创建MainWindow对象,只需将其更改为:
MainWindow mainWindow = Application.Current.MainWindow;
这里:
private void btnColumnIndexApply_Click(object sender, RoutedEventArgs e) { MainWindow originalForm = (MainWindow)Application.Current.MainWindow; //here int correctColumnNumber = int.Parse(txtColumnIndexCorrection.Text); column.Index = correctColumnNumber - 1; originalForm.UpdateSingleColumnIndex(column); originalForm.TriggerReadDataFile(this.filePath, this.fileExt, this.tableType); this.Close(); }