1
votes

I have the following WPF code and it gives me an exception at "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);
}
1
The same way people in those other questions with that exception fix it. Didn't you get a duplicate title error perchance and changed it afterwards? Either way, look to the right where it says "Related" -> - H.B.
There are definitely way too many. - H.B.
@H.B. - you have enough rep, pick one and vote to close. - Kev
@Kev: I do not want to waste my time looking for the dupe the poster should have looked for. Also it will never be closed as this question is soon burried among its kin, only returning in searches for the exception. - H.B.

1 Answers

3
votes

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.

You can do that instead:

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