C#:当链接到两个不同的对象时,如何检测谁是上下文菜单菜单项的调用者?

4 .net c# contextmenu menuitem winforms

C#:当链接到两个不同的对象时,如何检测谁是上下文菜单菜单项的调用者?

我有两个标签,lblOn和lblOff.我将"一个"上下文菜单链接到两个标签,以丢弃必须制作两个相同的标签.

我将如何找出名为contextmenu.menuitem的标签对象?这样点击菜单项就知道是不是它的上下文菜单是由lblOn标签还是lblOffline调用的?

SLa*_*aks 15

检查的SourceControl属性ContextMenuStrip.


小智 6

漠视.谷歌搜索后,我找到了解决方案+代码示例.

private void deleteToolStripMenuItem_Click(object sender, EventArgs e)
{
    //Make sure the sender is a ToolStripMenuItem
    ToolStripMenuItem myItem = sender as ToolStripMenuItem;
    if (myItem != null)
    {
        //Get the ContextMenuString (owner of the ToolsStripMenuItem)
        ContextMenuStrip theStrip = myItem.Owner as ContextMenuStrip;
        if (theStrip != null)
        {
            //The SourceControl is the control that opened the contextmenustrip.
            //In my case it could be a linkLabel
            LinkLabel linkLabel = theStrip.SourceControl as LinkLabel;
            if (linkLabel == null)
                MessageBox.Show("Invalid item selected.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            else
            {
                if (MessageBox.Show(string.Format("Are you sure you want to remove BOL {0} from this Job?", linkLabel.Text), "Confirm Delete", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    linkLabel.Text = Program.NullValue(linkLabel);
                }
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

资料来源:http://www.tek-tips.com/viewthread.cfm?qid = 1441041& page = 8