How do I update a Label from within a BackgroundWorker thread?

吃可爱长大的小学妹 提交于 2019-11-28 06:27:47

问题


When I used WinForms, I would have done this in my bg_DoWork method:

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

However in my WPF application I get an error saying that Invoke does not exist for Label.

Any help would be appreciated.


回答1:


This will help you.

To Execute synchronously:

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

To Execute Asynchronously:

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



回答2:


If you're using WPF, I'd suggest looking into DataBinding.

The "WPF way" to approach this would be to bind the label's Content property to some property of your model. That way, updating the model automatically updates the label and you don't have to worry marshalling the threads yourself.

There are many articles on WPF and databinding, this is likely as good a place to start as any: http://www.wpf-tutorial.com/data-binding/hello-bound-world/




回答3:


You need to use

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

instead of status.Invoke(...)




回答4:


You really should think about using the power of "Data Binding" in WPF.

You should be updating an object in your view model and binding that to your user interface control.

See MVVM Light. Simple and easy to use. Don't code WPF without it.



来源:https://stackoverflow.com/questions/30398006/how-do-i-update-a-label-from-within-a-backgroundworker-thread

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!