問題の 2 つの解決策を次に示します。1 つ目は元のコードに基づいていますが、どのイベントをターゲットにしているか 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
元のコードでは、親メニュー項目のみをループしていました。この更新されたコードでは、親アイテムの 'Status' を検索し、子アイテムをループして確認する必要があるステータスを見つけます。