EventHandler with custom arguments

旧街凉风 提交于 2019-12-17 16:21:56

问题


I've been looking for an answer for about an hour on Google but I did not found exactly what I'm looking for.

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 owner is the control in which I will associate my context menu.

Then later on I add a Click event to a MenuItem like this:

menuItemFolder.Click += new System.EventHandler(menuItemFolder_Click);

The problem I have here is that I want to pass "owner" and "dataType" as arguments to the menuItemFolder_Click event.

I tried the following:

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.

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?


回答1:


You should create a lambda expression that calls a method with the extra parameters:

menuItemFolder.Click += (sender, e) => YourMethod(owner, dataType);



回答2:


Honest admission up front: I have not tried the code below.

I think the reason

menuItemFolder.Click += new System.EventHandler(menuItemFolder_Click(sender,e,owner,dataType));

won't work is because you are actually passing to System.EventHandler () the result of the invocation of menuItemFolder_Click () with the parameters provided. You are not passing a pointer to the function itself.

Try to write another function that implements the details of menuItemFolder_Click (). See if something like

private void menuItemFolder_Click_Helper (object sender, EventArgs e, object Owner, object DataType) {
// implement details here
}

and then call the function from within menuItemFolder_Click ().




回答3:


I think the simplest code would be this:

    EventHandler myEvent = (sender, e) => MyMethod(myParameter);//my delegate

    myButton.Click += myEvent;//suscribe

    private void MyMethod(MyParameterType myParameter)
    {
     //Do something 

     //if only one time
     myButton.Click -= myEvent;//unsuscribe
    }


来源:https://stackoverflow.com/questions/6457474/eventhandler-with-custom-arguments

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!