从另一个线程读取复选框状态 [英] Reading Checkbox status from another thread

查看:83
本文介绍了从另一个线程读取复选框状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

正在尝试从WPF中的BackgroundWorker中读取复选框的值:

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

这不起作用:

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

无法将匿名方法转换为委托类型'System.Threading.ThreadStart',因为该块中的某些返回类型不能隐式转换为委托返回类型

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

编辑-这是HB的回答,是使用委托而不是lambda表示的,我觉得它更具可读性

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; }));

推荐答案

改为分配变量,则不需要return.

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

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

或者,您可以使用具有返回值的委托(例如, Func<T> ):

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

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

(要求在.NET 4.5之前强制返回类型)

这篇关于从另一个线程读取复选框状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆