应无所住,而生其心
排名
1
文章
860
粉丝
112
评论
163
net core webapi post传递参数
庸人 : 确实坑哈,我也是下班好了好几次,发现后台传递对象是可以的,但...
百度编辑器自定义模板
庸人 : 我建议换个编辑器,因为现在百度富文本已经停止维护了,用tinymec...
ICP备案 :渝ICP备18016597号-1
网站信息:2018-2025TNBLOG.NET
技术交流:群号656732739
联系我们:contact@tnblog.net
公网安备:50010702506256
欢迎加群交流技术

treeview右键菜单避免在空白处弹出来

5033人阅读 2018/10/11 17:20 总访问:5182441 评论:0 收藏:0 手机
分类: .NET


如果直接这样绑定在树形菜单中,在空白处也会弹出来的



思路应该是不直接绑定到控件,手动弹出菜单,弹出规则可以自定义,这样就会比较灵活了。弹出的逻辑我们可以绑定在树形的节点点击事件里边

  1. void treeView1_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
  2. {
  3.     if (e.Button == System.Windows.Forms.MouseButtons.Left)
  4.         return;
  5.     if (e.Node == null)
  6.         return;
  7.     //手动弹出菜单,弹出规则可以自定义,就会比较灵活了
  8.     contextMenuStrip.Show(treeView1, e.X, e.Y);
  9. }

完整一点的代码如下:

  1. namespace WindowsFormsApplication1
  2. {
  3.     public partial class Form1 : Form
  4.     {
  5.         ContextMenuStrip contextMenuStrip;
  6.         public Form1()
  7.         {
  8.             InitializeComponent();
  9.             treeView1.Nodes.Add("aa");
  10.             treeView1.Nodes.Add("bb");
  11.             treeView1.Nodes.Add("cc");
  12.             //右键菜单
  13.             contextMenuStrip = new System.Windows.Forms.ContextMenuStrip();
  14.             ToolStripMenuItem menuItem = new ToolStripMenuItem();
  15.             menuItem.Text = "子节点";
  16.             menuItem.Click += menuItem_Click;
  17.             ToolStripMenuItem toolStripDropDown = new ToolStripMenuItem();
  18.             toolStripDropDown.Text = "一级";
  19.             ToolStripMenuItem toolStripDropDown2 = new ToolStripMenuItem();
  20.             toolStripDropDown2.Text = "二级";
  21.             menuItem.DropDownItems.Add(toolStripDropDown);
  22.             menuItem.DropDownItems.Add(toolStripDropDown2);
  23.             contextMenuStrip.Items.Add(menuItem);
  24.             contextMenuStrip.Items.Add("修改");
  25.             contextMenuStrip.Items.Add("添加");
  26.             treeView1.ContextMenuStrip = contextMenuStrip;
  27.             treeView1.NodeMouseClick += treeView1_NodeMouseClick;
  28.         }
  29.         void treeView1_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
  30.         {
  31.             if (e.Button == System.Windows.Forms.MouseButtons.Left)
  32.                 return;
  33.             if (e.Node == null)
  34.                 return;
  35.             //手动弹出菜单,弹出规则可以自定义,就会比较灵活了
  36.             contextMenuStrip.Show(treeView1, e.X, e.Y);
  37.         }
  38.         void menuItem_Click(object sender, EventArgs e)
  39.         {
  40.             MessageBox.Show("点击");
  41.         }
  42.     }
  43. }


根据不同的节点弹出来不同的菜单
都能动态的弹出来菜单的,要根据不同的节点弹出不同的菜单也很简单,判断一下即可嘛,根据不同的条件,动态创建一下ContextMenuStrip然后在弹出来即可




欢迎加群讨论技术,1群:677373950(满了,可以加,但通过不了),2群:656732739。有需要软件开发,或者学习软件技术的朋友可以和我联系~(Q:815170684)

评价

饰心

2020/7/2 13:58:33

[哈哈][哈哈][哈哈][哈哈][哈哈]

剑轩:@饰心无法接受.jpg(假装有表情)

2020/7/2 14:36:36 回复