问题
I have a datagrid. I want to add columns as a result of an event. So I do
for (int iii = 1; iii <= 4; ++iii)
{
var dtgColumn = new DataGridTextColumn();
dtgColumn.Header = "AAA"
Dispatcher.Invoke((Action)(() => { dtgResults.Columns.Add(dtgColumn); }));
}
But despite using a dispatcher I get this error:
The calling thread cannot access this object because a different thread owns it.
Thank you for any help Patrick }
回答1:
It looks like a problem not a UI
control itself, but dtgColumn
object created. You are creating UI
element on one thread and add it to the UI
element on the main thread.
Change your code like:
Dispatcher.Invoke((Action)(() => {
var dtgColumn = new DataGridTextColumn();
dtgColumn.Header = "AAA"
dtgResults.Columns.Add(dtgColumn);
}));
So the object is created and added on the thread that owns UI
parent control.
来源:https://stackoverflow.com/questions/35293395/onevent-datagrid-column-add-fail