【发布时间】:2010-08-16 09:18:09
【问题描述】:
在我的 Windows 中,我有一个 TextBox,我想从另一个线程更新(文本属性)。这样做时,我得到 InvalidOperationException(见标题)。我在 google 中找到了不同的链接来解释这一点,但我似乎仍然无法使其工作。
我试过的是这样的:
Window1 代码:
private static Window1 _myWindow;
private MessageQueueTemplate _messageQueueTemplate;
private const string LocalTemplateName = "LocalExamSessionAccessCodeMessageQueueTemplate";
private const string RemoteTemplateName = "RemoteExamSessionAccessCodeMessageQueueTemplate";
...
public Window1()
{
InitializeComponent();
_myWindow = this;
}
public static Window1 MyWindow
{
get
{
return _myWindow;
}
}
public void LogText(string text)
{
informationTextBox.Text += text + Environment.NewLine;
}
...
在另一个类中(实际上是一个spring.NET Listener 适配器,监听某个队列,在另一个线程中启动)。
var thread = new Thread(
new ThreadStart(
delegate()
{
Window1.MyWindow.Dispatcher.Invoke(
System.Windows.Threading.DispatcherPriority.Normal,
new Action(
delegate()
{
Window1.MyWindow.LogText(text);
}
));
}
));
不会报错,只是Window1中LogText方法中的文本没有被触发,所以文本没有更新。
所以基本上,我想从另一个线程中运行的另一个类更新这个 TextBox 组件。
【问题讨论】:
标签: wpf multithreading