我有ContextMenuStrip
两个ToolStripItem
s 的设置。第二个ToolStripItem
有两个额外的嵌套ToolStripItem
s。我将其定义为:
ContextMenuStrip cms = new ContextMenuStrip();
ToolStripMenuItem contextJumpTo = new ToolStripMenuItem();
ToolStripMenuItem contextJumpToHeatmap = new ToolStripMenuItem();
ToolStripMenuItem contextJumpToHeatmapStart = new ToolStripMenuItem();
ToolStripMenuItem contextJumpToHeatmapLast = new ToolStripMenuItem();
cms.Items.AddRange(new ToolStripItem[] { contextJumpTo,
contextJumpToHeatmap});
cms.Size = new System.Drawing.Size(176, 148);
contextJumpTo.Size = new System.Drawing.Size(175, 22);
contextJumpTo.Text = "Jump To (No Heatmapping)";
contextJumpToHeatmap.Size = new System.Drawing.Size(175, 22);
contextJumpToHeatmap.Text = "Jump To (With Heatmapping)";
contextJumpToHeatmap.DropDownItems.AddRange(new ToolStripItem[] { contextJumpToHeatmapStart,
contextJumpToHeatmapLast });
contextJumpToHeatmapStart.Size = new System.Drawing.Size(165, 22);
contextJumpToHeatmapStart.Text = "From Start of File";
contextJumpToHeatmapLast.Size = new System.Drawing.Size(165, 22);
contextJumpToHeatmapLast.Text = "From Last Data Point";
ToolStripMenuItem
然后我为我想要响应的三个 s 的点击事件设置了一个事件监听器。以下是方法(我只列出了三种方法中的两种):
void contextJumpTo_Click(object sender, EventArgs e)
{
// Try to cast the sender to a ToolStripItem
ToolStripMenuItem menuItem = sender as ToolStripMenuItem;
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
DataGridView dgv = owner.SourceControl as DataGridView;
if (dgv != null)
// DO WORK
}
}
}
void contextJumpToHeatmapStart_Click(object sender, EventArgs e)
{
// Try to cast the sender to a ToolStripItem
ToolStripMenuItem menuItem = sender as ToolStripMenuItem;
if (menuItem != null)
{
// Retrieve the ToolStripItem that owns this ToolStripItem
ToolStripMenuItem ownerItem = menuItem.OwnerItem as ToolStripMenuItem;
if (ownerItem != null)
{
// Retrieve the ContextMenuStrip that owns this ToolStripItem
ContextMenuStrip owner = ownerItem.Owner as ContextMenuStrip;
if (owner != null)
{
// Get the control that is displaying this context menu
DataGridView dgv = owner.SourceControl as DataGridView;
if (dgv != null)
// DO WORK
}
}
}
}
这是我遇到的问题:
我的contextJumpTo_Click
方法效果很好。我们一直到我确定DataGridView
点击来自哪里,我可以继续。但是,它contextJumpTo
ToolStripMenuItem
不是ContextMenuStrip
.
但是我的方法contextJumpToHeatmapStart_Click
不起作用。当我到达我确定的那一行时owner.SourceControl
,它SourceControl
是空的,我无法继续。现在我知道这ToolStripMenuItem
是嵌套在 my 中的另一个之下ContextMenuStrip
,但为什么我的SourceControl
属性突然为空ContextMenuStrip
?
如何获得SourceControl
for a 嵌套ToolStripMenuItem
for a ContextMenuStrip
?