我想为我通过名称找到的控件添加一个处理程序。 问题是无法通过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
有没有更好的解决方案,然后这样做?
E.g。
之类的东西Dim Control as TypeName(MyObject).ToString = FindName(MyObject.Name.ToString)
答案 0 :(得分: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