C# TreeView 右键菜单
方法一:
在winform中,添加一个contextMenuStrip1,设置TreeView的属性ContextMenuStrip为contextMenuStrip1,并为这个contextMenuStrip1添加几个菜单项,点击每个菜单项,实现其click事件,然后添加treeivew的nodemouseclick事件,类似如下代码:
//右键菜单 private void treeView1_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e) { if (e.Button != MouseButtons.Right) return; if (e.Node.Parent == null || e.Node == null) return; treeView1.SelectedNode = e.Node; contextMenuStrip1.Show(tv_Roots, e.X, e.Y); } void contextMenuStripItem_Click(object sender, EventArgs e)//编辑飞行段 { }
方法二:不同节点对应不同的右键菜单(摘自http://www.cnblogs.com/imihiroblog/archive/2012/06/02/2531949.html)
private void tvOneRoot_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e) { if (e.Button != MouseButtons.Right) return; if (e.Node == null) return; //无节点 if (e.Node.Level == 0) return; int nodeType = GetNodeTypeByGuid(e.Node.Name); tvOneRoot.SelectedNode = e.Node; InitcmsOneRout(nodeType); cmsOneRout.Show(tvOneRoot, e.X, e.Y); } /// <summary> /// 初始化cmsOneRoot 从nodetype /// </summary> /// <param name="nodetype"></param> private void InitcmsOneRout(int nodetype) { cmsOneRout = new ContextMenuStrip(); if (nodetype == -1) { ToolStripMenuItem tmiEditRoutStation = new ToolStripMenuItem("编辑飞行站点"); tmiEditRoutStation.Click += new EventHandler(tmiEditRoutStation_Click); cmsOneRout.Items.Add(tmiEditRoutStation); ToolStripMenuItem tmiMoveRouteStation = new ToolStripMenuItem("更改位置"); tmiMoveRouteStation.Click += new EventHandler(tmiMoveRouteStation_Click); cmsOneRout.Items.Add(tmiMoveRouteStation); ToolStripMenuItem tmiDeleRouteStation = new ToolStripMenuItem("删除飞行站点"); tmiDeleRouteStation.Click += new EventHandler(tmiDeleRouteStation_Click); cmsOneRout.Items.Add(tmiDeleRouteStation); } else if (nodetype == 0) { ToolStripMenuItem tmiEditRout = new ToolStripMenuItem("编辑飞行段属性"); tmiEditRout.Click += new EventHandler(tmiEditRout_Click); cmsOneRout.Items.Add(tmiEditRout); ToolStripMenuItem tmiDeleteRout = new ToolStripMenuItem("删除飞行段"); tmiDeleteRout.Click += new EventHandler(tmiDeleteRout_Click); cmsOneRout.Items.Add(tmiDeleteRout); } else if (nodetype == 1) { } else if (nodetype == 2) { } else { } } void tmiEditRout_Click(object sender, EventArgs e)//编辑飞行段 { string routId = tvOneRoot.SelectedNode.Name; RouteParameter rp = GetRouteParaByGuid(routId); FrmPointProperty frm = new FrmPointProperty(rp, 0, 1); frm.OnRoutInfoUpdated += new FrmPointProperty.DelegateRouteInfoUpdated(frm_OnRoutInfoUpdated); frm.ShowDialog(); }