treeview右键菜单避免在空白处弹出来
电脑版发表于:2018/10/11 17:20
如果直接这样绑定在树形菜单中,在空白处也会弹出来的
思路应该是不直接绑定到控件,手动弹出菜单,弹出规则可以自定义,这样就会比较灵活了。弹出的逻辑我们可以绑定在树形的节点点击事件里边
void treeView1_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e) { if (e.Button == System.Windows.Forms.MouseButtons.Left) return; if (e.Node == null) return; //手动弹出菜单,弹出规则可以自定义,就会比较灵活了 contextMenuStrip.Show(treeView1, e.X, e.Y); }
完整一点的代码如下:
namespace WindowsFormsApplication1 { public partial class Form1 : Form { ContextMenuStrip contextMenuStrip; public Form1() { InitializeComponent(); treeView1.Nodes.Add("aa"); treeView1.Nodes.Add("bb"); treeView1.Nodes.Add("cc"); //右键菜单 contextMenuStrip = new System.Windows.Forms.ContextMenuStrip(); ToolStripMenuItem menuItem = new ToolStripMenuItem(); menuItem.Text = "子节点"; menuItem.Click += menuItem_Click; ToolStripMenuItem toolStripDropDown = new ToolStripMenuItem(); toolStripDropDown.Text = "一级"; ToolStripMenuItem toolStripDropDown2 = new ToolStripMenuItem(); toolStripDropDown2.Text = "二级"; menuItem.DropDownItems.Add(toolStripDropDown); menuItem.DropDownItems.Add(toolStripDropDown2); contextMenuStrip.Items.Add(menuItem); contextMenuStrip.Items.Add("修改"); contextMenuStrip.Items.Add("添加"); treeView1.ContextMenuStrip = contextMenuStrip; treeView1.NodeMouseClick += treeView1_NodeMouseClick; } void treeView1_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e) { if (e.Button == System.Windows.Forms.MouseButtons.Left) return; if (e.Node == null) return; //手动弹出菜单,弹出规则可以自定义,就会比较灵活了 contextMenuStrip.Show(treeView1, e.X, e.Y); } void menuItem_Click(object sender, EventArgs e) { MessageBox.Show("点击"); } } }
根据不同的节点弹出来不同的菜单
都能动态的弹出来菜单的,要根据不同的节点弹出不同的菜单也很简单,判断一下即可嘛,根据不同的条件,动态创建一下ContextMenuStrip然后在弹出来即可