如何修复 WPF 应用上的"The calling thread cannot access this object because a different thread owns it."



我有以下WPF代码,它给了我一个例外在"TextBox t = tabItem。这个错误说"调用线程不能访问这个对象,因为另一个线程拥有它。"如何修复异常?

问候!

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);
}

UI对象的属性和方法只能在创建这些对象的线程上访问,所以当你试图在工作线程上访问tabItem.Content时,它会失败。

你可以这样做:

TextBox t;
Window1.myWindow1.Dispatcher.Invoke(new Action(() => t = tabItem.Content as TextBox));

相关内容