我有一个ContextMenuStrip分配给几个不同的列表框。我试图弄清楚ContextMenuStrip什么时候单击了什么ListBox。我尝试将下面的代码作为开始,但无法正常工作。在sender有正确的价值,但是当我尝试它分配到menuSubmitted它为空。
ContextMenuStrip
ListBox
sender
menuSubmitted
private void MenuViewDetails_Click(object sender, EventArgs e) { ContextMenu menuSubmitted = sender as ContextMenu; if (menuSubmitted != null) { Control sourceControl = menuSubmitted.SourceControl; } }
任何帮助都会很棒。谢谢。
使用以下帮助,我弄清楚了:
private void MenuViewDetails_Click(object sender, EventArgs e) { ToolStripMenuItem menuItem = sender as ToolStripMenuItem; if (menuItem != null) { ContextMenuStrip calendarMenu = menuItem.Owner as ContextMenuStrip; if (calendarMenu != null) { Control controlSelected = calendarMenu.SourceControl; } } }
ContextMenu
问题是该sender参数指向单击的上下文菜单上的 项目 ,而不是上下文菜单本身。
不过,这是一个简单的解决方法,因为每个方法都MenuItem公开了一个GetContextMenu方法,该方法将告诉您哪个ContextMenu包含该菜单项。
MenuItem
GetContextMenu
将您的代码更改为以下内容:
private void MenuViewDetails_Click(object sender, EventArgs e) { // Try to cast the sender to a MenuItem MenuItem menuItem = sender as MenuItem; if (menuItem != null) { // Retrieve the ContextMenu that contains this MenuItem ContextMenu menu = menuItem.GetContextMenu(); // Get the control that is displaying this context menu Control sourceControl = menu.SourceControl; } }
如果使用a ContextMenuStrip而不是a,它的确会稍有改变ContextMenu。这两个控件彼此不相关,并且一个实例不能转换为另一个实例。
与以前一样,被单击的 项目 仍会在sender参数中返回,因此您将必须确定ContextMenuStrip拥有此单独菜单项的。您可以通过该Owner属性来实现。最后,您将使用该SourceControl属性来确定哪个控件正在显示上下文菜单。
Owner
SourceControl
像这样修改您的代码:
private void MenuViewDetails_Click(object sender, EventArgs e) { // Try to cast the sender to a ToolStripItem ToolStripItem menuItem = sender as ToolStripItem; if (menuItem != null) { // Retrieve the ContextMenuStrip that owns this ToolStripItem ContextMenuStrip owner = menuItem.Owner as ContextMenuStrip; if (owner != null) { // Get the control that is displaying this context menu Control sourceControl = owner.SourceControl; } } }