【发布时间】:2022-01-10 11:24:09
【问题描述】:
我有一个 UserControl,它有几个通过 VS Designer 添加的 ContextMenuStrips。它们在设计时没有分配给任何控件,因为它们被动态分配给一个上下文敏感的“下拉”按钮。我有一个类,它遍历控件中的所有控件以主题化这些控件(即暗模式)。代码:
Private ControlList As List(Of Control) = New List(Of Control)()
Private Sub GetAllControls(ByVal container As Control)
For Each c As Control In container.Controls
GetAllControls(c)
ControlList.Add(c)
Next
End Sub
未检测到上下文菜单条。通过阅读,我了解到这些不是控件,而是组件。我尝试了一种建议的解决方案:
Private Sub GetAllComponents(container As Object)
For Each co As System.ComponentModel.Component In container.components.Components
If TypeOf co Is ContextMenuStrip Then
ControlList.Add(co)
End If
Next
End Sub
但是我在运行时遇到错误:
System.MissingMemberException: 'Public member 'components' on type 'ObjectSelector' not found.'
ObjectSelector 是 UserControl。
主题类被许多其他对象(窗体、用户控件)使用,因此很难为这个用户控件拥有一个特定的属性。如何获取 UserControl 上所有 ContextMenuStrips 的列表?
【问题讨论】:
-
components是表单的私有成员字段。所以需要使用反射来获取。
标签: .net vb.net winforms user-controls contextmenustrip