3

Am trying to read the value of a checkbox from a BackgroundWorker in WPF:

This doesn't work:

bool? isSleepChecked = checkBoxSleep.Dispatcher.Invoke(DispatcherPriority.Normal, (ThreadStart)delegate{ return checkBoxSleep.IsChecked;});

Cannot convert anonymous method to delegate type 'System.Threading.ThreadStart' because some of the return types in the block are not implicitly convertible to the delegate return type

EDIT - Here is HB's answer expressed using a delegate instead of lambda which I find slightly more readable

bool? isSleepChecked = (bool?)checkBoxSleep.Dispatcher.Invoke(new Func<bool?>(delegate { return checkBoxSleep.IsChecked; }));
Dave Mateer
  • 6,588
  • 15
  • 76
  • 125

2 Answers2

6

Assign the variable instead, then you don't need a return.

bool? isSleepChecked;
checkBoxSleep.Dispatcher.Invoke(new Action(
    () => isSleepChecked = checkBoxSleep.IsChecked));

Alternatively you can use a delegate with return value (e.g. a Func<T>):

bool? isSleepChecked = checkBoxSleep.Dispatcher.Invoke(new Func<bool?>(
                            () => checkBoxSleep.IsChecked));

(Requires return type cast before .NET 4.5)

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

Your code will not compile because, whilst you are attempting to return a bool? from your delegate, ThreadStart has a return type of void.

The easiest approach in such cases would probably be to capture your isSleepChecked variable within a lambda expression and set it directly:

bool? isSleepChecked = null;
checkBoxSleep.Dispatcher.Invoke(new Action(() =>
{ 
    isSleepChecked = checkBoxSleep.IsChecked; 
}), 
    DispatcherPriority.Normal);
Douglas
  • 53,759
  • 13
  • 140
  • 188