当我点击另一个菜单项时,我想取消选中MenuStrip中主ToolStripMenuItem(称为MyMainMenu)的所有菜单项。主菜单包含一些菜单项和一个分隔符。我尝试了以下代码:
Private Sub CheckCheckedStatusMenu(ByVal MnuItem As ToolStripMenuItem)
MnuItem.Checked = True
For Each Mnu As ToolStripMenuItem In Me.MyMainMenu.DropDownItems
If Not Mnu Is MnuItem Then
Mnu.Checked = False
End If
Next
End Sub
我从每个菜单项调用该代码(除了分隔符)。当我点击一个菜单项时,程序崩溃了,说他不能从ToolStripSeparator转换为ToolStripMenuItem。相同的代码可以在Microsoft.NET文档网站上找到,用于类似的目的,但它没有指定在同一菜单项包含不同类型的项(分隔符、文本框…)的情况下可以做什么
你知道我该怎么解决这个问题吗?
谢谢,
再见
您的代码假设DropDownItems
只返回类型为ToolStripmenuItem
的项,但实际上它返回了一个ToolstripItemCollection
因此,你需要进行额外的检查,以确保你只使用你感兴趣的类型:
Private Sub CheckCheckedStatusMenu(ByVal MnuItem As ToolStripMenuItem)
MnuItem.Checked = True
For Each item In Me.MyMainMenu.DropDownItems
If TypeOf item Is ToolStripMenuItem Then
Dim mnu = CType(item, ToolStripMenuItem)
If Not mnu Is MnuItem Then
mnu.Checked = False
End If
End If
Next
End Sub
也许一个更好的选择是过滤你的原始集合,只返回特定类型的对象:
Private Sub CheckCheckedStatusMenu(ByVal MnuItem As ToolStripMenuItem)
MnuItem.Checked = True
For Each mnu In Me.MyMainMenu.DropDownItems.OfType(Of ToolStripMenuItem)
If Not mnu Is MnuItem Then
mnu.Checked = False
End If
Next
End Sub
请注意,您可以进一步简化您的例程,只检查传入的项目:
Private Sub CheckCheckedStatusMenu(ByVal MnuItem As ToolStripMenuItem)
For Each mnu In Me.MyMainMenu.DropDownItems.OfType(Of ToolStripMenuItem)
mnu.Checked = (mnu Is MnuItem)
Next
End Sub