更新WPF在运行时控制 [英] Update WPF controls at run time

查看:122
本文介绍了更新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?

推荐答案

是的,但你必须使用更新的 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的一个例子可以在这里找到:<一href="http://stackoverflow.com/questions/1754827/wpf-update-ui-from-viewmodel-class-mvvm-pattern/1754848#1754848">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.

这篇关于更新WPF在运行时控制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆