Over the forum and on MSDN they have given a clear way to access the UI controls from different thread using Dispatcher.Invoke. But, when in UI thread, how do I access a WPF component ex DataGrid created on a different thread ?
In my situation, I start a thread to handle a long process. In this thread I create a DataTable, and bind it to a DataGrid which is also created in this thread.
Now, when it is time to display the DataGrid, I appropriately call the Dispatcher.Invoke on a UI control. But, when I try to access the DataGrid in my UI thread, I get an exception -The calling thread cannot access this object because a different thread owns it.
Any suggestion please ..
public void AddResultsController(ResultsController controller)
{
NewResultsControllerDisplayDelegate newControllerDisplayDelegate = new NewResultsControllerDisplayDelegate(NewResultsControllerDisplay);
this.docManager.Dispatcher.BeginInvoke(newControllerDisplayDelegate, System.Windows.Threading.DispatcherPriority.Normal, controller);
}
delegate void NewResultsControllerDisplayDelegate(ResultsController controller);
private void NewResultsControllerDisplay(ResultsController controller)
{
Grid grd = new Grid();
grd.Children.Add(controller.SummaryDataGrid); // Exception is thrown here
}
In my background thread I call…
m_mainWindow.AddResultsController(m_controller);
You simply do not create UI-elements on background threads. Make your life easier and follow that rule.