SourceControl of ContextMenuStrip is Nothing in ToolStripMenuItem Click?

蓝咒 提交于 2019-12-08 12:50:11

问题


I have single ContextMenuStrip attached to more controls.

In use the Opening event of ContextMenuStrip to filter/disable some context entries. In this case the property ContexteMenuStrip.SourceControl is set correctly.

The problem I have is on the Click event of a ToolStripMenuItem. This item is inside a ToolStripDropDown.

I get the parent item with code:

Dim tsmi As ToolStripMenuItem = DirectCast(DirectCast(DirectCast(sender, ToolStripMenuItem).Owner, ToolStripDropDown).OwnerItem, ToolStripMenuItem)

then I get the ContextMenuStrip:

Dim contextMenu As ContextMenuStrip = DirectCast(tsmi.Owner, ContextMenuStrip)

but now, if I check contextMenu.SourceControl is Nothing.

Do you have any idea what is wrong or why SourceControl is not set in this case?

Thank you in advance


回答1:


I found a workaround that is not really the answer to the question. So I will leave it open for a while.

I used the ContextMenuStrip Opening event to store locally the source object.

Private Sub contextGrid_Opening(ByVal sender As System.Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles contextGrid.Opening

  _ContextSourceGrid = DirectCast(contextGrid.SourceControl, DataGridView)

End Sub

and refer directly to the saved object inside all ToolStripMenuItem Click events.




回答2:


Try this:

DirectCast(DirectCast(DirectCast(
    tsmi.Owner, System.Windows.Forms.ToolStrip).
    TopLevelControl, System.Windows.Forms.Control),
    System.Windows.Forms.ContextMenuStrip).SourceControl



回答3:


I had this exact same question a couple weeks ago, and in reality, nobody could figure out why this behavior was occurring. Take a look at the question I asked, the solution I was given worked great.



来源:https://stackoverflow.com/questions/3091555/sourcecontrol-of-contextmenustrip-is-nothing-in-toolstripmenuitem-click

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!