如何从BackgroundWorker线程中更新标签?
当我使用WinForms时,我会在我的bg_DoWork
方法中完成此bg_DoWork
:
status.Invoke(new Action(() => { status.Content = e.ToString(); })); status.Invoke(new Action(() => { status.Refresh(); }));
但是在我的WPF应用程序中,我收到一条错误,指出Label
不存在Invoke
。
任何帮助,将不胜感激。
这对你有所帮助。
要同步执行:
Application.Current.Dispatcher.Invoke(new Action(() => { status.Content = e.ToString(); }))
要异步执行:
Application.Current.Dispatcher.BeginInvoke(new Action(() => { status.Content = e.ToString(); }))
使用BackgroundWorker
已内置的function。 当您“报告进度”时,它会将您的数据发送到在UI线程上运行的ProgressChanged
事件。 无需调用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,我建议您查看DataBinding。
接近这个的“WPF方式”是将标签的Content
属性绑定到模型的某个属性。 这样,更新模型会自动更新标签,您不必担心自己编组线程。
关于WPF和数据绑定的文章很多,这可能是一个很好的起点: http : //www.wpf-tutorial.com/data-binding/hello-bound-world/
你需要使用
Dispatcher.Invoke(new Action(() => { status.Content = e.ToString(); }))
而不是status.Invoke(...)
你真的应该考虑在WPF中使用“数据绑定”的强大function。
您应该更新视图模型中的对象并将其绑定到用户界面控件。
请参阅MVVM Light。 简单易用。 没有它就不要编写WPF代码。