我终于能够通过向包含递归搜索的类添加一个事件处理程序来实现这一点。当我为目录中的每个文件设置文件对象的名称时,设置一个 onPropertyChanged 事件。我将它与我的后台工作人员的 DoWork 中的表格联系起来。然后我在事件触发时报告了进度,并使用后台工作程序 ProgressChanged 将文本设置为当前文件名。以下是我的程序中的一些代码片段,可以帮助任何尝试类似事情的人。
在搜索类
foreach (string file in Directory.GetFiles(dir))
{
//creating objects for each file in the directory
FileObject fileObject = new FileObject();
FileInfo info = new FileInfo(file);
currentfile = file.ToString();
fileObject.name = info.Name.ToString();
fileObject.path = file.ToString();
fileObject.createdDate = info.CreationTime.ToString();
FileList.Add(fileObject);
//event handler triggered
OnFileNameChanged(name);
}
//event handler code
public event PropertyChangedEventHandler PropertyChanged;
protected void OnFileNameChanged(string propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
在 windows 窗体中
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
//do some work
search.PropertyChanged += (s, pe) => backgroundWorker1.ReportProgress(unusedNumber);
backgroundWorker1.ReportProgress(100);
}
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
//change label
label1.Text = search.currentfile;
}