问题描述
我在 Google 上找了大约一个小时的答案,但没有找到我想要的答案.
I've been looking for an answer for about an hour on Google but I did not found exactly what I'm looking for.
基本上,我有一个静态 Helper 类,可以帮助执行我在应用程序中经常做的许多事情.在这种情况下,我有一个名为CreateDataContextMenu"的方法,它在给定的 TreeView 控件上创建上下文菜单.
Basically, I have a static Helper class that helps perform many things I do frequently in my App. In this case, I have a method named "CreateDataContextMenu" that creates a context menu on a given TreeView control.
public static void CreateDataContextMenu(Form parent, TreeView owner, string dataType)
{ ... }
TreeView 所有者是我将关联上下文菜单的控件.
TreeView owner is the control in which I will associate my context menu.
稍后我将 Click 事件添加到 MenuItem,如下所示:
Then later on I add a Click event to a MenuItem like this:
menuItemFolder.Click += new System.EventHandler(menuItemFolder_Click);
我在这里遇到的问题是我想将所有者"和数据类型"作为参数传递给 menuItemFolder_Click 事件.
The problem I have here is that I want to pass "owner" and "dataType" as arguments to the menuItemFolder_Click event.
我尝试了以下方法:
menuItemFolder.Click += new System.EventHandler(menuItemFolder_Click(sender,e,owner,dataType));
(...)
private static void menuItemFolder_Click(object sender, System.EventArgs e, Treeview owner, string dataType)
{...}
但它根本不起作用.这样做可能太天真了,但我对事件处理程序还不是很满意.
But it doesn't work at all. It might be very naive of me to do it that way but I"m not very comfortable with event handler yet.
知道我该怎么做吗?我的第一个猜测是我需要为这种特定情况创建自己的 EventHandler.我是否朝着正确的方向前进?
Any idea on how I could do that? My first guess is that I need to create my own EventHandler for this specific case. Am I going in the right direction with that?
推荐答案
你应该创建一个 lambda 表达式 调用带有额外参数的方法:
You should create a lambda expression that calls a method with the extra parameters:
menuItemFolder.Click += (sender, e) => YourMethod(owner, dataType);
这篇关于带有自定义参数的 EventHandler的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!