14

I am trying to call a selected listbox item from a button, not the listbox.selecteditemchanged method in wpf. So when i try

string yadda = listbox.SelectedItem.ToString();

i get an exception:

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

So, what i was trying to do is the following:

Dispatcher.BeginInvoke(() =>
                    {
                        lbxSelectedItem =  (lbxFileList.SelectedItem as TextBlock).Text;
                    });

That is not working either because i get another exception:

Cannot convert lambda expression to type 'System.Delegate' because it is not a delegate type

Cœur
  • 37,241
  • 25
  • 195
  • 267
darthwillard
  • 809
  • 2
  • 14
  • 28
  • BeginInvoke requires an argument of type Delegate, not enough type info to convince the C# compiler to accept a lamda. Other than casting to Action or MethodInvoker, an anonymous method still works best. – Hans Passant May 31 '11 at 02:00

1 Answers1

27

Convert the lambda to an Action:

Dispatcher.BeginInvoke((Action)(() => { /*DoStuff*/ }));

Or construct one from the lambda:

Dispatcher.BeginInvoke(new Action(() => { /*DoStuff*/ }));

You probably can write an extension method for the Dispatcher that takes an Action, that way the lambda would be implicitly converted.

H.B.
  • 166,899
  • 29
  • 327
  • 400