当我点击另一个菜单项时,我想在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文档站点上找到相同的代码,但它没有指定在相同的菜单项包含不同类型的项目(分隔符,文本框...)的情况下可以执行的操作。
你知道我该如何解决这个问题吗?
谢谢,
再见
答案 0 :(得分:0)
您的代码假定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