2016-02-09 51 views
0

我有一個數據網格。我想添加列作爲事件的結果。 所以我做OnEvent datagrid列添加失敗

for (int iii = 1; iii <= 4; ++iii) 
{ 
    var dtgColumn = new DataGridTextColumn(); 
    dtgColumn.Header = "AAA" 
    Dispatcher.Invoke((Action)(() => { dtgResults.Columns.Add(dtgColumn); })); 
} 

但是,儘管使用一個調度程序我得到這個錯誤:

The calling thread cannot access this object because a different thread owns it.

感謝您的幫助 帕特里克 }

+0

嘗試使用Application.Current.Dispatcher。有關更多詳細信息,請參閱此處:http://stackoverflow.com/questions/10448987/dispatcher-currentdispatcher-vs-application-current-dispatcher –

+0

唉,不像以前那樣工作 – Patrick

+0

dtgResults定義在哪裏,它在哪裏實例化? (哪個線程?) –

回答

1

它看起來像一個問題不是一個UI控制本身,但dtgColumn對象創建。您正在一個線程上創建UI元素,並將其添加到主線程上的UI元素。

Dispatcher.Invoke((Action)(() => { 
     var dtgColumn = new DataGridTextColumn(); 
     dtgColumn.Header = "AAA" 

     dtgResults.Columns.Add(dtgColumn); 
    })); 

所以被創建並添加擁有UI父控件的線程上的對象:喜歡

更改代碼。

+1

這個問題與我在一個叫做代碼的事實有關功能。所以我將Dispatcher添加到函數中,並且它工作正常。所以它和你的解決方案是一樣的。 – Patrick