更新WPF在运行时控制WPF

由网友(亽苼勞資說ㄋ匴)分享简介:我试着写一个WPF应用程序,它会在运行时使用线程更新一组文本框和标签,但问题是,当过一个线程试图更新文本框和标签,我得到了以下错误: 调用线程不能访问此对象,因为不同的线程拥有它。是否有可能更新在运行时的控制?I'm trying to write a WPF application that will update...

我试着写一个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?

推荐答案

是的,但你必须使用更新的 Dispatcher.Invoke 。

Yes, but you have to update the UI elements in the UI thread using Dispatcher.Invoke.

实例在C#中:而不是

myTextBox.Text = myText;

使用

Dispatcher.Invoke(new Action(() => myTextBox.Text = myText));

VB.NET(前4版)不支持匿名方法,所以你必须用一个匿名函数解决方法是:

VB.NET (before version 4) does not support anonymous methods, so you'll have to workaround it with an anonymous function:

Dispatcher.Invoke(Function() UpdateMyTextBox(myText))

...

Function UpdateMyTextBox(ByVal text As String) As Object
    myTextBox.Text = text
    Return Nothing
End Function

另外,您也可以使用启动后台线程 BackgroundWorker的类,它通过 ProgressChanged RunWorkerCompleted 事件支持在用户界面的更新:这两个事件都引发了UI自动线程。使用BackgroundWorker的一个例子可以在这里找到:SO问题1754827 。

Alternatively, you can start your background threads using the BackgroundWorker class, which support updates in the UI through the ProgressChanged and RunWorkerCompleted events: Both events are raised in the UI thread automatically. An example for using BackgroundWorker can be found here: SO question 1754827.

阅读全文

相关推荐

最新文章