如何获取打开ContextMenuStrip的控件?

How to get the control which opened the ContextMenuStrip?
2021-06-20
  •  译文(汉语)
  •  原文(英语)

我正在寻找一种使程序具有导致ContextMenuStrip打开的控件的方法.我为多个组合框分配了相同的Strip以重用它们,就像在课程开始时一样.

myComboBox.ContextMenuStrip = changevaluestrip;

在这里,我有"添加值"和"删除值",当然,它们中的每一个都必须知道必须从哪个组合框中删除值.我尝试用

private void removeValueToolStrip_Click(object sender, EventArgs e)
{
    ToolStripMenuItem usedbox = sender as ToolStripMenuItem;
    var parent = usedbox.GetCurrentParent();
    DialogResult res = MessageBox.Show("Do you really want to delete this value?", "Delete Value", MessageBoxButtons.YesNo);
    if (res == DialogResult.Yes)
    {
        //Delete it from the combobox it was sent from
    }
}

但这并没有真正解决,只是给了我"发件人的价值" ...

解决过程1

是的,@ KingKing是正确的.您需要ContextMenuStrip.SourceControl为此目的使用.这是为您执行此操作的代码段.

ToolStripMenuItem usedbox = sender as ToolStripMenuItem;
ContextMenuStrip parent = usedbox.GetCurrentParent() as ContextMenuStrip;
if (parent != null)
{
    ComboBox combo = parent.SourceControl as ComboBox;
    if (combo != null)
    { 
         //use combobox here   
    }
}
解决过程2

也许ContextMenuStrip.SourceControl是您想要的.

I'm looking for a way to give the program the control which caused the ContextMenuStrip to open. I'm assigning the same Strip for multiple comboboxes to reuse them, like this at the start of the class.

myComboBox.ContextMenuStrip = changevaluestrip;

Here I have "Add Value" and "Delete Value", and of course each of these has to know which from which combobox it has to delete the value. I tried doing it with

private void removeValueToolStrip_Click(object sender, EventArgs e)
{
    ToolStripMenuItem usedbox = sender as ToolStripMenuItem;
    var parent = usedbox.GetCurrentParent();
    DialogResult res = MessageBox.Show("Do you really want to delete this value?", "Delete Value", MessageBoxButtons.YesNo);
    if (res == DialogResult.Yes)
    {
        //Delete it from the combobox it was sent from
    }
}

But that didn't really work out and just gave me "Remove Value" as sender...

Solutions1

Yes, @KingKing is right. You need to use ContextMenuStrip.SourceControl for this purpose. Here is a snippet doing that for you.

ToolStripMenuItem usedbox = sender as ToolStripMenuItem;
ContextMenuStrip parent = usedbox.GetCurrentParent() as ContextMenuStrip;
if (parent != null)
{
    ComboBox combo = parent.SourceControl as ComboBox;
    if (combo != null)
    { 
         //use combobox here   
    }
}
Solutions2

Maybe ContextMenuStrip.SourceControl is what you want.

转载于:https://stackoverflow.com/questions/18571326/how-to-get-the-control-which-opened-the-contextmenustrip

本人是.net程序员,因为英语不行,使用工具翻译,希望对有需要的人有所帮助
如果本文质量不好,还请谅解,毕竟这些操作还是比较费时的,英语较好的可以看原文

留言回复
我们只提供高质量资源,素材,源码,坚持 下了就能用 原则,让客户花了钱觉得值
上班时间 : 周一至周五9:00-17:30 期待您的加入