2011-09-14 38 views
1

在論壇和MSDN上,他們已經給出了一個清晰的方法來使用Dispatcher.Invoke從不同線程訪問UI控件。但是,在UI線程中,如何訪問在不同線程上創建的DataGrid的WPF組件?如何訪問在UI線程中的不同線程上創建的DataGrid?

在我的情況下,我開始一個線程來處理一個漫長的過程。在這個線程中,我創建一個DataTable,並將其綁定到也在此線程中創建的DataGrid。

現在,當顯示DataGrid的時候,我適當地調用UI控件上的Dispatcher.Invoke。但是,當我嘗試訪問我的UI線程中的DataGrid時,出現異常 - 調用線程無法訪問此對象,因爲不同的線程擁有它。

任何建議,請..

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 
} 

在我的後臺線程我叫......

m_mainWindow.AddResultsController(m_controller); 
+0

我想使用Dispatcher.Invoke()是正確的做法。 你可以發佈你的代碼? – Thinhbk

+0

已發佈我的代碼.. –

+0

請幫助...我卡住了,無法繼續前進。 –

回答

1

您只需就不要在後臺線程上創建UI元素。讓你的生活更輕鬆,遵循這個規則。

+0

這就是我所做的。謝謝 –

0

試試這個:

public void AddResultsController(ResultsController controller) 
{ 
    NewResultsControllerDisplayDelegate newControllerDisplayDelegate = new NewResultsControllerDisplayDelegate(NewResultsControllerDisplay); 
    Grid grd = new Grid(); 
    grd.Children.Add(controller.SummaryDataGrid); 
    this.docManager.Dispatcher.BeginInvoke(newControllerDisplayDelegate, System.Windows.Threading.DispatcherPriority.Normal, grd); 
} 

delegate void NewResultsControllerDisplayDelegate(ResultsController controller); 
private void NewResultsControllerDisplay(Grid grd) 
{ 
    this.docManager.Add(grd); 
} 

H個。

+0

獲取此錯誤消息 - 調用線程不能訪問此對象,因爲不同的線程擁有它。 –

+0

我想知道controller.SummaryDataGrid,它是一個用戶控件還是數據? 如果它是一個usercontrol,那麼它屬於哪個線程? – Thinhbk

+0

SummaryDataGrid是在後臺工作線程中創建的DataGrid。它在運行時分配了一個DataTable –

相關問題