在运行时更新 WPF 控件
我正在尝试编写一个 WPF 应用程序,该应用程序将使用线程在运行时更新一组文本框和标签,但问题是,当线程尝试更新文本框和标签时,我会收到以下错误:“调用线程无法访问该对象,因为另一个线程拥有它。”是否可以在运行时更新控件?
I'm trying to write a WPF application that will update a set of text boxes and labels at run time using threads but the problem is that when ever a thread tries to update the text boxes and labels I get the following error: "The calling thread cannot access this object because a different thread owns it." Is it possible to update the control at run time?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
是的,但您必须使用 Dispatcher.Invoke。
C# 中的示例:而不是
使用
VB.NET(版本 4 之前)不支持匿名方法,因此您必须使用匿名函数来解决它:
或者,您可以使用 BackgroundWorker 类,支持通过
ProgressChanged< 在 UI 中进行更新/code> 和
RunWorkerCompleted
事件:这两个事件都会在 UI 线程中自动引发。使用BackgroundWorker的示例可以在这里找到: SO问题1754827。Yes, but you have to update the UI elements in the UI thread using Dispatcher.Invoke.
Example in C#: Instead of
use
VB.NET (before version 4) does not support anonymous methods, so you'll have to workaround it with an anonymous function:
Alternatively, you can start your background threads using the BackgroundWorker class, which support updates in the UI through the
ProgressChanged
andRunWorkerCompleted
events: Both events are raised in the UI thread automatically. An example for using BackgroundWorker can be found here: SO question 1754827.WPF 中的控件有一个
Dispatcher
属性,您可以在该属性上调用Invoke
,传递一个委托以及您想要在 GUI 线程上下文中执行的代码。Controls in WPF have a
Dispatcher
property on which you can callInvoke
, passing a delegate with the code you'd like to execute in the context of the GUI thread.