0

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 }

Patrick
  • 3,073
  • 2
  • 22
  • 60
  • Try use Application.Current.Dispatcher. for more details, see here:http://stackoverflow.com/questions/10448987/dispatcher-currentdispatcher-vs-application-current-dispatcher – Василий Шапенко Feb 09 '16 at 13:41
  • Alas not working same as before – Patrick Feb 09 '16 at 13:44
  • Where is dtgResults defined, and where is it instantiated? (which thread?) – John Feb 09 '16 at 13:48
  • There is a main thread which trough xaml defines the datagrid: then I run a thread command which resides in a library and when the finished event occurs I do add the new columns. So 1 main thread and one event from another thread. – Patrick Feb 09 '16 at 14:01
  • try the "Application.Current.Dispatcher" instead of just Dispatcher. I think you're getting the wrong one somehow. – John Feb 09 '16 at 14:13
  • ВасилийШапенко already suggested it but it's not working. Would you elaborate what I'm getting wrong? Please not that if I put all that in a button and operate on the button click it works... – Patrick Feb 09 '16 at 14:19
  • I also added AutoGenerateColumns="False" but no change – Patrick Feb 09 '16 at 14:24

1 Answers1

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.

Tigran
  • 61,654
  • 8
  • 86
  • 123
  • 1
    The problem was related with the fact that I was calling that code in a function. So I added the Dispatcher to the function and it worked. So it's the same solution as yours. – Patrick Feb 19 '16 at 13:53