我需要帮助项目检查工具条菜单项

时间:2015-01-24 05:14:42

标签: vb.net toolstripitem

我在这里有一个专栏......我想要做的是当我选择一个项目时

enter image description here

我希望根据列

中的状态检查上下文菜单中的项目

enter image description here

这是我到目前为止的尝试

 Dim currentItem As ToolStripMenuItem = DirectCast(sender, ToolStripMenuItem)
    Dim parentItem = DirectCast(currentItem.OwnerItem, ToolStripMenuItem)
    For Each ctl As ToolStripMenuItem In parentItem.DropDownItems
        If TypeOf ctl Is ToolStripMenuItem Then
            If ctl.Text = ListView1.SelectedItems.Item(0).Text Then
                currentItem = DirectCast(ctl, ToolStripMenuItem)
                currentItem.Checked = True
            End If
        End If
    Next

但只是给了我什么。我怎么能转过身来?自昨晚以来一直在努力奋斗......提前付款

1 个答案:

答案 0 :(得分:2)

以下是您的问题的两种可能解决方案。第一个更多地基于您的原始代码,我不能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

接下来是我用来测试此功能的实际代码。我使用上下文菜单的Opening事件来完成这项工作。如果您为不同的列或控件重复使用相同的上下文菜单,这可能不适合您,但如果没有,那么我会推荐这种方法:

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

在原始代码中,您只是遍历父菜单项。在此更新的代码中,它会查找父项'状态'然后遍历子项以查找需要检查的状态。