OnEvent datagrid column add fail

2019-09-04 02:59发布

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条回答
不美不萌又怎样
2楼-- · 2019-09-04 03:15

It looks like a problem not a UI control itself, but dtgColumnobject 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.

查看更多
登录 后发表回答