我如何添加一个上下文菜单到ListBoxItem的? [英] How can I add a context menu to a ListBoxItem?

查看:148
本文介绍了我如何添加一个上下文菜单到ListBoxItem的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个列表框,我想一个上下文菜单列表中添加到每个项目。我见过的解决方案有右键选择一个项目,如果在空白抑制上下文菜单中,但这种方法感觉很脏。

I have a ListBox and I want to add a context menu to each item in the list. I've seen the "solution" to have the right click select an item and suppress the context menu if on white space, but this solution feels dirty.

有谁知道一个更好的办法?

Does anyone know a better way?

推荐答案

这方式菜单旁边弹出鼠标

This way the menu will pop up next to the mouse

private string _selectedMenuItem;
private readonly ContextMenuStrip collectionRoundMenuStrip;

public Form1()
{ 
    var toolStripMenuItem1 = new ToolStripMenuItem {Text = "Copy CR Name"};
    toolStripMenuItem1.Click += toolStripMenuItem1_Click;
    var toolStripMenuItem2 = new ToolStripMenuItem {Text = "Get information on CR"};
    toolStripMenuItem2.Click += toolStripMenuItem2_Click;
    collectionRoundMenuStrip = new ContextMenuStrip();
    collectionRoundMenuStrip.Items.AddRange(new ToolStripItem[] {toolStripMenuItem1, toolStripMenuItem2 });
    listBoxCollectionRounds.MouseDown += listBoxCollectionRounds_MouseDown;
}

private void toolStripMenuItem2_Click(object sender, EventArgs e)
{
    var info = GetInfoByName(_selectedMenuItem);
   MessageBox.Show(info.Name + Environment.NewLine + info.Date);
}

private void toolStripMenuItem1_Click(object sender, EventArgs e)
{
    Clipboard.SetText(_selectedMenuItem);
}

private void myListBox_MouseDown(object sender, MouseEventArgs e)
{
    if (e.Button != MouseButtons.Right) return;
    var index = myListBox.IndexFromPoint(e.Location);
    if (index != ListBox.NoMatches)
    {
        _selectedMenuItem = listBoxCollectionRounds.Items[index].ToString();
        collectionRoundMenuStrip.Show(Cursor.Position);
        collectionRoundMenuStrip.Visible = true;
    }
    else
    {
        collectionRoundMenuStrip.Visible = false;
    }
}

这篇关于我如何添加一个上下文菜单到ListBoxItem的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆