【问题标题】:How can I add a context menu to a ListBoxItem?如何将上下文菜单添加到 ListBoxItem?
【发布时间】:2010-09-27 11:24:09
【问题描述】:

我有一个 ListBox,我想为列表中的每个项目添加一个上下文菜单。我已经看到“解决方案”可以右键单击选择一个项目并在空白处抑制上下文菜单,但这个解决方案感觉很脏。

有人知道更好的方法吗?

【问题讨论】:

  • 你不能用其他方式设计它吗?我想不出任何这样的用户界面...我永远不会想到右键单击列表框项。
  • 你也在 Winforms 或 WPF 中吗?答案可能会有所不同。

标签: c# winforms listbox contextmenu


【解决方案1】:

进一步详细说明 Frans 所说的内容...即使 ListBox 拥有 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() ) );
}

希望有所帮助。

【讨论】:

  • 我收到一个错误,即 listboxContextMenu_Opening 在当前上下文中不存在。
  • 谢谢,但为什么你没有提到onClick 参数或其他方式为菜单项设置Click 事件?
【解决方案2】:

这样菜单会在鼠标旁边弹出

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

【讨论】:

  • 我认为您的代码缺少负载listBoxCollectionRounds.ContextMenuStrip=collectionRoundMenuStrip
【解决方案3】:

没有其他方法:上下文菜单不属于列表框中的项目,而是属于列表框本身。它类似于树视图控件,它也拥有上下文菜单而不是树节点。所以每当列表框中的一个项目被选中时,根据选中的项目设置列表框的上下文菜单。

【讨论】:

    【解决方案4】:

    这是我的解决方案:

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

    【讨论】:

      【解决方案5】:

      在 XAML 中显示如下:

      <ListBox>
          <ListBox.ContextMenu>
              <ContextMenu>
                  <MenuItem Header="Add User..."/>
                  <MenuItem Header="Edit..."/>
                  <MenuItem Header="Disable"/>
              </ContextMenu>
          </ListBox.ContextMenu>
      </ListBox>
      

      【讨论】:

        【解决方案6】:

        一行代码(更多用于绑定):

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

        【讨论】:

          【解决方案7】:

          如果只是启用或禁用上下文菜单项的问题,那么仅在启动上下文菜单时而不是每次列表框选择更改时才这样做可能更有效:

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

          【讨论】:

            【解决方案8】:

            这个最好...

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

            【讨论】:

              【解决方案9】:
              //Create and Initialize the contextMenuStrip component
              contextMenuStrip_ListaAulas = new ContextMenuStrip();
              
              //Adding an Item
              contextMenuStrip_ListaAulas.Items.Add("Modificar");
              
              //Binding the contextMenuStrip with the ListBox
              listBox_Aulas.ContextMenuStrip = contextMenuStrip_ListaAulas;
              
              //The solution below 
              if (e.Button == System.Windows.Forms.MouseButtons.Right)
              {
                  //select the item under the mouse pointer
                  listBox_Aulas.SelectedIndex = listBox_Aulas.IndexFromPoint(e.Location);
              
                  //if the selected index is an item, binding the context MenuStrip with the listBox
                  if (listBox_Aulas.SelectedIndex != -1)
                  {
                       listBox_Aulas.ContextMenuStrip = contextMenuStrip_ListaAulas;  
                  }
                  //else, untie the contextMenuStrip to the listBox 
                  else
                  {
                       listBox_Aulas.ContextMenuStrip = null;
                  }
              }
              

              【讨论】:

                【解决方案10】:

                我喜欢这个,这对我来说效果很好而且速度很快。

                private void contextMenuStrip1_Opening(object sender, CancelEventArgs e)
                    {
                        if (Listbox.SelectedItem == null)
                            e.Cancel = true;
                    }
                

                【讨论】:

                  猜你喜欢
                  • 1970-01-01
                  • 1970-01-01
                  • 1970-01-01
                  • 1970-01-01
                  • 1970-01-01
                  • 2017-04-27
                  • 1970-01-01
                  • 1970-01-01
                  • 2017-06-29
                  相关资源
                  最近更新 更多