问题描述
在Windows中,我有一个TextBox,我想从另一个线程更新(文本属性).这样做时,我得到InvalidOperationException(请参见标题).我在Google中找到了不同的链接来对此进行解释,但我似乎仍然无法使其正常工作.
In my Windows I have a TextBox which I like to update (text property) from another thread. When doing so, I get the InvalidOperationException (see title). I have found different links in google explaining this, but I still can't seem to make it work.
我尝试过的是这个
Window1代码:
Window1 code:
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适配器,用于侦听某个队列,是在另一个线程中启动的.)
In another class (actually a spring.NET Listener adapter, listening to a certain queue, started in another thread).
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方法中的文本,因此不会更新文本.
It doesn't throw an error, but the text in the LogText method in Window1 isn't triggered, so the text isn't updated.
所以基本上,我想从在另一个线程中运行的另一个类更新此TextBox组件.
So basically, I want to update this TextBox component from another class running in another thread.
推荐答案
Window1.MyWindow.informationTextBox.Dispatcher.Invoke(
DispatcherPriority.Normal,
new Action(() => Window1.MyWindow.informationTextBox.Text += value));
这篇关于WPF System.InvalidOperationException:调用线程无法访问此对象,因为另一个线程拥有它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!