OnEvent datagrid column add fail

吃可爱长大的小学妹 提交于 2020-01-07 03:43:07

问题


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 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.



来源:https://stackoverflow.com/questions/35293395/onevent-datagrid-column-add-fail

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!