[英]How to fix “The calling thread cannot access this object because a different thread owns it.” on a WPF app
I have the following WPF code and it gives me an exception at "TextBox t = tabItem.Content as TextBox;" 我有以下WPF代码,它在“ TextBox t = tabItem.Content as TextBox;”处给了我一个例外。 the error says "The calling thread cannot access this object because a different thread owns it."
错误说“调用线程无法访问此对象,因为另一个线程拥有它。” How can I fix the exception?
我该如何修复异常?
Regards! 问候!
private void btnAdd_Click(object sender, RoutedEventArgs e)
{
RichTextBox statusRichTextBox = new RichTextBox();
CloseableTabItem tabItem = new CloseableTabItem();
tabItem.Content = statusRichTextBox;
tabItem.Header = "New Tab";
MainTab.Items.Add(tabItem);
Thread t = new Thread(new ParameterizedThreadStart(worker));
t.Start(tabItem);
}
public void worker(object threadParam)
{
CloseableTabItem tabItem = (CloseableTabItem)threadParam;
TextBox t = tabItem.Content as TextBox; //exception here
if (t != null)
Window1.myWindow1.Dispatcher.BeginInvoke((Action)(() => { t.Text = "THIS IS THE TEXT"; }), System.Windows.Threading.DispatcherPriority.Normal);
}
Properties and methods of UI objects can only be accessed on the thread that created these objects, so when you try to access tabItem.Content
on a worker thread, it fails. UI对象的属性和方法只能在创建这些对象的线程上访问,因此当您尝试访问工作线程上的
tabItem.Content
时,它会失败。
You can do that instead: 您可以改为:
TextBox t;
Window1.myWindow1.Dispatcher.Invoke(new Action(() => t = tabItem.Content as TextBox));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.