1

有没有办法为支持它的未指定 Windows 控件检查和设置 Checked 属性?

当然,还有蛮力方法:

If TypeOf (control) Is Windows.Forms.CheckBox Then
    Dim chk As Windows.Forms.CheckBox = control
    chk.Checked = Boolean.Parse(sText)
ElseIf TypeOf (control) Is Windows.Forms.RadioButton Then
    Dim rdo As Windows.Forms.RadioButton = control
    rdo.Checked = Boolean.Parse(sText)
ElseIf TypeOf (control) Is Windows.Forms.DateTimePicker Then
    Dim dte As Windows.Forms.DateTimePicker = control
    dte.Checked = Boolean.Parse(sText)
etc...

但是,我确实觉得那很难看,并且可能会错过一些控件。

似乎没有支持该属性的超类,甚至对于CheckBoxand 。RadioButton此外,尝试简单地设置control.Checked不会编译。

如果你好奇我在做什么,我希望创建一个通用表来存储命名控件的默认值。

4

1 回答 1

3

如果您真的想检查任何名为 的属性的存在Checked,那么您需要使用反射:

control.GetType().GetProperty("Checked") IsNot Nothing

Checked(请注意,如果重载,这将引发异常。)

但是你真的只想保存Checkeda 的属性DateTimePicker吗?看起来你正在寻找一个列表:

Private Shared ReadOnly CheckableTypes() As New HashSet(Of Type)({
    GetType(CheckBox), GetType(RadioButton), ...
})
...
If CheckableTypes.Contains(control.GetType()) Then
于 2012-11-19T15:07:39.767 回答