简体   繁体   English

在以编程方式填充后单击时,如何获取上下文菜单条中项目的文本?

[英]How can i get the text of an item in context menu strip when clicked after populated programmatically?

I'm trying to get the text of an ITEM in CONTEXT MENU STRIP when CLICKED after generated on runtime.我试图在运行时生成后单击时获取 CONTEXT MENU STRIP 中 ITEM 的文本。 I have already populated the ITEMS in CONTEXT MENU STRIP and added an event handler for click.我已经在 CONTEXT MENU STRIP 中填充了 ITEMS 并为点击添加了一个事件处理程序。 The problem is I really don't know how to get the text of those items.问题是我真的不知道如何获取这些项目的文本。

private void updateContext()
        {
            a_context_menu.Items.Clear();

            foreach (var a_device in a_devices)
            {
                var a_item = a_context_menu.Items.Add("A CONTEXT");
                var a_item = a_context_menu.Items.Add("B CONTEXT");

                a_item.Click += a_item_Click;
            }
        }

        private void a_item_Click(object sender, EventArgs e)
        {
            MessageBox.Show(a_item_Click.text);
        }

TYI泰益

if a_context is clicked a message box will show with that item's text:如果单击 a_context,将显示一个消息框,其中包含该项目的文本:

a_context a_context

Cast the "sender" to "ToolStripItem"将“发件人”投射到“ToolStripItem”

private void A_item_Click(object sender, EventArgs e)
{
    MessageBox.Show(((ToolStripItem)sender).Text);
}

and... by the way, before you clear the items:还有……顺便说一句,在你清除物品之前:

contextMenuStrip1.Items.Clear();

you need to remove the click event:您需要删除点击事件:

foreach (ToolStripItem ts in contextMenuStrip1.Items)
{
    ts.Click -= A_item_Click;
}

contextMenuStrip1.Items.Clear();

Or there's a memory leak happens.或者发生 memory 泄漏。

just found the delegate function and i think it's the better approach.刚找到代表 function,我认为这是更好的方法。

    private void updateContextMenu()
    {    
         foreach (var a_device in a_devices)
         {
              var a_item = a_context_menu.Items.Add(aDevice.FullName);
              a_item.Click += delegate {
              a_item_Click(a_Device.FullName);
              };
    
         }
     }
    
    private void Mic_item_Click(string deviceName)
    {
         MessageBox.Show(a_deviceName);
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM