如何从BackgroundWorker线程更新标签?当我使用WinForms时,我在我的bg_DoWork方法中这样做:status.Invoke(newAction(()=>{status.Content=e.ToString();}));status.Invoke(newAction(()=>{status.Refresh();}));但是在我的WPF应用程序中,我收到一个错误,指出Label不存在Invoke。任何帮助将不胜感激。这对你有帮助。同步执行:Application.Current.Dispatcher.Invoke(newAction(()=>{status.Content=e.ToString();}))异步执行:Application.Current.Dispatcher.BeginInvoke(newAction(())=>{status.Content=e.ToString();}))使用BackgroundWorker的内置函数。当您“报告进度”时,它会将您的数据发送到在UI线程上运行的ProgressChanged事件。无需调用Invoke()。privatevoidbgWorker_DoWork(objectsender,DoWorkEventArgse){bgWorker.ReportProgress(0,"要显示的消息。");}privatevoidbgWorker_ProgressChanged(objectsender,ProgressChangedEventArgse){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(newAction(()=>{status.Content=e.ToString();}))而不是status.Invoke(...)您真的应该考虑在WPF中使用“数据绑定”的功能。您应该更新视图模型中的对象并将它们绑定到UI控件。请参见MVVMLight。简单易用。没有它就不要编写WPF代码。以上是C#学习教程:HowtoupdatethelabelfromtheBackgroundWorkerthread?如果所有分享的内容对你有用,需要进一步了解C#学习教程,希望大家多多关注。本文收集自网络,不代表立场。如涉及侵权,请点击右侧联系管理员删除。如需转载请注明出处:
