如何从BackgroundWorker线程中更新Label ?

本文关键字:更新 Label 线程 BackgroundWorker | 更新日期: 2023-09-27 17:50:28

当我使用WinForms时,我会在我的bg_DoWork方法中这样做:

status.Invoke(new Action(() => { status.Content = e.ToString(); }));
status.Invoke(new Action(() => { status.Refresh(); }));

然而,在我的WPF应用程序中,我得到一个错误说Invoke不存在Label

如何从BackgroundWorker线程中更新Label ?

使用BackgroundWorker中已经内置的功能。当你"报告进度"时,它将你的数据发送到ProgressChanged事件,该事件在UI线程上运行。不需要调用Invoke()

private void bgWorker_DoWork(object sender, DoWorkEventArgs e)
{
    bgWorker.ReportProgress(0, "Some message to display.");
}
private void bgWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
    status.Content = e.UserState.ToString();
}

确保您设置bgWorker.WorkerReportsProgress = true以启用报告进度

如果您正在使用WPF,我建议您查看一下数据绑定。

解决这个问题的"WPF方式"是将标签的Content属性绑定到模型的某些属性。这样,更新模型会自动更新标签,您不必担心自己编组线程。

有很多关于WPF和数据绑定的文章,这可能是一个很好的起点:http://www.wpf-tutorial.com/data-binding/hello-bound-world/

这对你有帮助。

同步执行:

Application.Current.Dispatcher.Invoke(new Action(() => { status.Content = e.ToString(); }))

异步执行:

Application.Current.Dispatcher.BeginInvoke(new Action(() => { status.Content = e.ToString(); }))

你需要使用

Dispatcher.Invoke(new Action(() => { status.Content = e.ToString(); }))

代替status.Invoke(...)

你真的应该考虑在WPF中使用"数据绑定"的强大功能。

你应该更新视图模型中的对象,并将其绑定到用户界面控件。

参见MVVM Light。简单易用。在编写WPF时不要缺少它