Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/331.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何将上下文菜单添加到ListBoxItem?_C#_Winforms_Listbox_Contextmenu - Fatal编程技术网

C# 如何将上下文菜单添加到ListBoxItem?

C# 如何将上下文菜单添加到ListBoxItem?,c#,winforms,listbox,contextmenu,C#,Winforms,Listbox,Contextmenu,我有一个列表框,我想为列表中的每个项目添加一个上下文菜单。我见过“解决方案”,右键单击选择一个项目,如果在空白处,则抑制上下文菜单,但这个解决方案感觉脏 有人知道更好的方法吗?没有其他方法:关联菜单不属于列表框中的项目,而是属于列表框本身。它类似于treeview控件,它也拥有上下文菜单而不是treenode。因此,每当选择列表框中的某个项目时,根据所选项目设置列表框的上下文菜单 只需对Frans所说的做进一步阐述……即使列表框拥有ContextMenuStrip,您仍然可以在菜单条打开时自定义

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


有人知道更好的方法吗?

没有其他方法:关联菜单不属于列表框中的项目,而是属于列表框本身。它类似于treeview控件,它也拥有上下文菜单而不是treenode。因此,每当选择列表框中的某个项目时,根据所选项目设置列表框的上下文菜单

只需对Frans所说的做进一步阐述……即使列表框拥有ContextMenuStrip,您仍然可以在菜单条打开时自定义菜单条中的项目。因此,可以根据鼠标在列表框中的位置自定义其内容

下面的示例基于鼠标右键单击选择列表框中的项目,然后基于用户右键单击的项目自定义上下文菜单条。这是一个简单的示例,但应该让您开始:向表单添加列表框并添加以下代码:

#region Private Members
private ContextMenuStrip listboxContextMenu;
#endregion

private void Form1_Load( object sender, EventArgs e )
{
    //assign a contextmenustrip
    listboxContextMenu = new ContextMenuStrip();
    listboxContextMenu.Opening +=new CancelEventHandler(listboxContextMenu_Opening);
    listBox1.ContextMenuStrip = listboxContextMenu;

    //load a listbox
    for ( int i = 0; i < 100; i++ )
    {
        listBox1.Items.Add( "Item: " + i );
    }
}

private void listBox1_MouseDown( object sender, MouseEventArgs e )
{
    if ( e.Button == MouseButtons.Right )
    {
        //select the item under the mouse pointer
        listBox1.SelectedIndex = listBox1.IndexFromPoint( e.Location );
        if ( listBox1.SelectedIndex != -1)
        {
            listboxContextMenu.Show();   
        }                
    }
}

private void listboxContextMenu_Opening( object sender, CancelEventArgs e )
{
    //clear the menu and add custom items
    listboxContextMenu.Items.Clear();
    listboxContextMenu.Items.Add( string.Format( "Edit - {0}", listBox1.SelectedItem.ToString() ) );
}
#地区私人会员
私有ContextMenuStrip listboxContextMenu;
#端区
私有void Form1\u加载(对象发送方、事件参数e)
{
//分配一个contextmenustrip
listboxContextMenu=新建ContextMenuStrip();
listboxContextMenu.Opening+=新的CancelEventHandler(listboxContextMenu_Opening);
listBox1.ContextMenuStrip=listboxContextMenu;
//加载列表框
对于(int i=0;i<100;i++)
{
列表框1.Items.Add(“Item:+i”);
}
}
私有无效列表框1u MouseDown(对象发送方,MouseEventArgs e)
{
如果(e.按钮==鼠标按钮.右)
{
//选择鼠标指针下的项目
listBox1.SelectedIndex=listBox1.IndexFromPoint(如位置);
如果(listBox1.SelectedIndex!=-1)
{
listboxContextMenu.Show();
}                
}
}
private void listboxContextMenu_打开(对象发送方,取消事件参数e)
{
//清除菜单并添加自定义项
listboxContextMenu.Items.Clear();
添加(string.Format(“编辑-{0}”,listBox1.SelectedItem.ToString());
}

希望有帮助。

如果只是启用或禁用关联菜单项的问题,那么只在启动关联菜单时执行,而不是每次列表框选择更改时执行,可能会更有效:

myListBox.ContextMenu.Popup += new EventHandler(myContextPopupHandler);


private void myContextPopupHandler(Object sender, System.EventArgs e)
{
    if (SelectedItem != null)
    {
        ContextMenu.MenuItems[1].Enabled = true;
        ContextMenu.MenuItems[2].Enabled = true;
    }
    else
    {
        ContextMenu.MenuItems[1].Enabled = false;
        ContextMenu.MenuItems[2].Enabled = false;
    }
}

在XAML中,它显示如下:



这是最好的…

using System.Windows.Forms;

ContextMenuStrip menu;

this.menu.Items.AddRange(new ToolStripItem[] { this.menuItem });
this.listBox.MouseUp += new MouseEventHandler(this.mouse_RightClick);

private void mouse_RightClick(object sender, MouseEventArgs e)
{
    int index = this.listBox.IndexFromPoint(e.Location);
    if (index != ListBox.NoMatches)
    {
        menu.Visible = true;
    }
    else
    {
        menu.Visible = false;
    }
}

这是我的解决方案:

listBox_Usernames.ContextMenuStrip = contextMenuStripRemove;
listBox_Usernames.MouseUp += new MouseEventHandler(listBox_Usernames_MouseUp);

void listBox_Usernames_MouseUp(object sender, MouseEventArgs e)
{
    int index = listBox_Usernames.IndexFromPoint(e.Location);
    if (e.Button == System.Windows.Forms.MouseButtons.Right)
    {
        if (index != ListBox.NoMatches)
        {
            if (listBox_Usernames.SelectedIndex == index)
            {
                listBox_Usernames.ContextMenuStrip.Visible = true;
            }
            else
            {
                listBox_Usernames.ContextMenuStrip.Visible = false;
            }
        }
        else
        {
            listBox_Usernames.ContextMenuStrip.Visible = false;
        }
    }
    else
    {
        listBox_Usernames.ContextMenuStrip.Visible = false;
    }
}

这样,菜单将在鼠标旁边弹出

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;
    }
}

我很喜欢这个,它对我来说又快又好用

private void contextMenuStrip1_Opening(object sender, CancelEventArgs e)
    {
        if (Listbox.SelectedItem == null)
            e.Cancel = true;
    }
在一行代码中(更多用于绑定):

var datasource=newbindingslist(newlist(newstring[]{“item1”}));
listbox.DataSource=数据源;
listbox.ContextMenu=新建ContextMenu(
新菜单项[]{
新菜单项(“删除”,
新事件处理程序((s,ev)=>
datasource.Remove(listbox.SelectedItem.ToString())
)
) 
});
私有无效按钮单击(对象发送者,事件参数e)
{
添加(textBox.Text);
}   

您不能用其他方式设计它吗?我想不出任何像这样的用户界面。。。我从来没有想过右键单击列表框项目。您是否也使用Winforms或WPF?答案可能会有所不同。我发现一个错误,listboxContextMenu_在当前上下文中不存在。谢谢,但是,为什么您没有在单击参数时提到
,或者以其他方式设置菜单项的
单击
事件?我认为您的代码缺少加载
listBoxCollectionRounds.ContextMenuStrip=collectionRoundMenuStrip
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;
    }
}
private void contextMenuStrip1_Opening(object sender, CancelEventArgs e)
    {
        if (Listbox.SelectedItem == null)
            e.Cancel = true;
    }
var datasource = new BindingList<string>( new List<string>( new string[] { "item1" } ) );
listbox.DataSource = datasource ;
listbox.ContextMenu = new ContextMenu(
    new MenuItem[] { 
        new MenuItem("Delete", 
            new EventHandler( (s,ev) => 
            datasource.Remove(listbox.SelectedItem.ToString())
        )
    ) 
});

private void buttonAdd_Click(object sender, EventArgs e)
{
    datasource.Add( textBox.Text );
}