1

我想将一个处理程序添加到我通过其名称找到的控件中。问题是无法从 Button 或 RadioButton 或类似的东西对控件进行调暗...

Dim control As Control = FindName(MyObject.Name.ToString)
            AddHandler control.MouseEnter, Sub()
                                               Try
                                                   Dim Tooltip As New ToolTip()
                                                   Tooltip.SetToolTip(control, control.Name.ToString)
                                               Catch

                                               End Try

                                           End Sub

在代码中,我可以将控件调暗为 Button,但随后例如 RadioButtons 将不起作用。而且我不希望有一个总是检查 ObjectType 然后进入 if 部分的代码

If TypeName(MyObject).ToString = "Button" then
...
else if TypeName(MyObject).ToString = "Label" then
...
else if TypeName(MyObject).ToString = "RadioButton" then
...
End If

有没有更好的解决方案然后这样做?

例如像

Dim Control as TypeName(MyObject).ToString = FindName(MyObject.Name.ToString)
4

1 回答 1

1

这就是你所追求的吗?

For Each ctr As Control In Me.Controls
    AddHandler ctr.MouseEnter, Sub()
                                   Try
                                       Dim Tooltip As New ToolTip()
                                       Tooltip.SetToolTip(ctr, ctr.Name.ToString)
                                   Catch

                                   End Try
                               End Sub
Next

如果您正在循环访问面板等父对象,则需要将其扩展到每个孩子,但这个概念应该有效。

编辑

这应该适用于任何有孩子的控件:

在表单/类的顶部声明:

Private _controls As New List(Of Control)

使用它来添加处理程序:

For Each ctr As Control In Me.Controls
    AddHandler ctr.MouseEnter, Sub()
                                   Try
                                       Dim Tooltip As New ToolTip()
                                       Tooltip.SetToolTip(ctr, ctr.Name.ToString)
                                   Catch

                                   End Try
                               End Sub
    If ctr.HasChildren Then
        _controls = New List(Of Control)
        GetChildren(ctr)
        For Each childCtr As Control In _controls
            AddHandler childCtr.MouseEnter, Sub()
                                                Try
                                                    Dim Tooltip As New ToolTip()
                                                    Tooltip.SetToolTip(childCtr, childCtr.Name.ToString)
                                                Catch

                                                End Try
                                            End Sub
        Next
    End If
Next

像这样的东西会_controls用子控件填充列表:

Private Sub GetChildren(ByVal container As Control)

    For Each childCtr As Control In container.Controls
        _controls.Add(childCtr)
        If childCtr.HasChildren Then
            GetChildren(childCtr)
        End If
    Next

End Sub
于 2016-10-28T10:40:35.840 回答