当为上下文菜单构建单击事件方法时,Event Args
传递单击事件的内容是什么?
我试图建立一个树列表上下文菜单,以便当我右键单击一个文件夹,我有创建一个新文件夹的选项。我想弄清楚的是如何传递被点击的文件夹,这样我就可以在正确的位置创建文件夹。
这是我目前为止写的:
private void qList_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
{
if(e.Button == System.Windows.Forms.MouseButtons.Right)
{
ContextMenu cm = new ContextMenu();
//folder or file
if(e.Node.ImageKey == "folder")
{
cm.MenuItems.Add(new MenuItem("Create New Folder",CreateNewFolder_Click));
cm.MenuItems.Add("Create New QPack");
cm.MenuItems.Add("Remove New Folder");
e.Node.ContextMenu = cm;
}
else if (e.Node.ImageKey == "files")
{
cm.MenuItems.Add("Create QPack", CreateNewQPack_Click);
cm.MenuItems.Add("Remove QPack");
e.Node.ContextMenu = cm;
}
}
}
private void CreateNewFolder_Click(object sender, EventArgs e)
{
}
private void CreateNewQPack_Click(object sender, EventArgs e)
{
}
您可以简单地创建一个匿名事件处理程序,它将捕获任何相关数据并将其传递给不同的方法:
var menuItem = new MenuItem(
"Create New Folder",
// the following lambda will capture the `e` parameter
(sender, args) => DoSomething(e.Node, "stuff just happened"));
另一种方法是创建自己的自定义菜单项,如下所示:
public class CustomMenuItem : MenuItem
{
public TreeNode SelectedTreeNode { get; set; }
public CustomMenuItem(string text, EventHandler onClick, TreeNode treeNode) : base(text, onClick)
{
SelectedTreeNode = treeNode;
}
}
与其像这样创建菜单项
cm.MenuItems.Add(new MenuItem("Create New Folder",CreateNewFolder_Click));
你做:
cm.MenuItems.Add(new CustomMenuItem("Create New Folder", CreateNewFolder_Click, e.Node));
然后你将在你的方法中得到你的TreeNode,像这样:
private void CreateNewFolder_Click(object sender, EventArgs e)
{
CustomMenuItem customMenuItem = sender as CustomMenuItem;
MessageBox.Show(customMenuItem.SelectedTreeNode.FullPath);
}