以下是您的问题的两种可能的解决方案。第一个更多地基于您的原始代码,我不能 100% 确定您针对的是哪个事件,所以我无法对其进行测试:
Dim currentItem As ToolStripMenuItem = DirectCast(sender, ToolStripMenuItem)
Dim parentItem = DirectCast(currentItem.OwnerItem, ToolStripMenuItem)
For Each ctl As ToolStripMenuItem In parentItem.DropDownItems
If ctl.Text = "Status" Then
For Each dropctl As ToolStripMenuItem In ctl.DropDownItems
If dropctl.Text = ListView1.SelectedItems.Item(0).Text Then
dropctl.Checked = True
Else
dropctl.Checked = False ' Ensure that you uncheck a previously checked status
End If
Next
End If
Next
接下来是我用来测试此功能的实际代码。我使用上下文菜单的打开事件来完成这项工作。如果您对不同的列或控件重复使用相同的上下文菜单,这可能对您不起作用,但如果不是,那么我会推荐这种方法:
Private Sub ContextMenuStrip1_Opening(sender As Object, e As System.ComponentModel.CancelEventArgs) Handles ContextMenuStrip1.Opening
If ListView1.SelectedItems.Count > 0 Then
For Each ctl As ToolStripMenuItem In CType(sender, System.Windows.Forms.ContextMenuStrip).Items
If ctl.Text = "Status" Then
For Each dropctl As ToolStripMenuItem In ctl.DropDownItems
If dropctl.Text = ListView1.SelectedItems.Item(0).Text Then
dropctl.Checked = True
Else
dropctl.Checked = False ' Ensure that you uncheck a previously checked status
End If
Next
End If
Next
Else
e.Cancel = True ' Don't show the context menu if no row was clicked on
End If
End Sub
在您的原始代码中,您仅循环通过父菜单项。在此更新后的代码中,它会查找父项“状态”,然后遍历子项以查找您需要检查的状态。