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