如题,为了实现点击树不同级别节点右键显示不同的菜单功能。
例如点击Group节点并右键显示 编辑、删除、新增Node的功能;点击Node节点并右键只显示 编辑、删除的功能;在空白处又只显示新建Group的功能。
1.首先在VS里新建一个Windows窗体应用,再从工具箱中拖出一个Treeview控件和一个contextMenuStript控件,右键控件适当添加一些节点和选项。
2.控件拉好后,点中treeview控件,在界面右下角的属性中选中事件,查找并双击NodeMouseClick
添加代码该事件的代码(其中this后的AddGroupToolStripMenuItem等,为contextMenuStrip里各选项的Name)
private void treeView1_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
{
if (e.Button == MouseButtons.Right)//判断点击的是否为右键
{
if (e.Node.Level == 0)//如果是第一级节点处右键,显示菜单
{
this.AddGroupToolStripMenuItem.Visible = false;//Visible为false时隐藏选项,true为显示;Enabled指是否禁用
this.EditGroupToolStripMenuItem.Visible = true;
this.DeleteGroupToolStripMenuItem.Visible = true;
this.AddNodeToolStripMenuItem.Visible = true;
this.EditNodeToolStripMenuItem.Visible = false;
this.DeleteNodeToolStripMenuItem.Visible = false;
}
else if (e.Node.Level == 1)//如果是第二级节点右键,显示菜单
{
this.AddGroupToolStripMenuItem.Visible = false;
this.EditGroupToolStripMenuItem.Visible = false;
this.DeleteGroupToolStripMenuItem.Visible = false;
this.AddNodeToolStripMenuItem.Visible = false;
this.EditNodeToolStripMenuItem.Visible = true;
this.DeleteNodeToolStripMenuItem.Visible = true;
}
this.treeView1.SelectedNode = e.Node;
}
}
3.随后选择双击treeview控件的MouseDown事件,添加代码如下:
private void treeView1_MouseDown(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
return;
}
else
{
if (sender == treeView1)
{
this.AddGroupToolStripMenuItem.Visible = true;
this.EditGroupToolStripMenuItem.Visible = false;
this.DeleteGroupToolStripMenuItem.Visible = false;
this.AddNodeToolStripMenuItem.Visible = false;
this.EditNodeToolStripMenuItem.Visible = false;
this.DeleteNodeToolStripMenuItem.Visible = false;
this.treeView1.SelectedNode = null;
}
}
}
4.结果
5.以上代码为参考下列网址,如有侵权,请联系删除
http://www.voidcn.com/article/p-ryixbaci-vv.html?tdsourcetag=s_pctim_aiomsg