简体   繁体   English

如何将附加参数添加到按钮单击EventHandler?

[英]How can I add an additional parameter to a button click EventHandler?

In C#, how is the best way to add an additional property to a button event call? 在C#中,向按钮事件调用添加其他属性的最佳方法是什么?

Here is the code for the EventHandler : 这是EventHandler的代码:

button.Click += new EventHandler(button_Click);

Here is the code for the button_Click : 这是button_Click的代码:

private void button_Click(object sender, EventArgs e)
{

}

If I want to add a PropertyGrid parameter to the button_Click function parameters, how is the best way to do this? 如果我想将PropertyGrid参数添加到button_Click函数参数,最好的方法是什么?

I am wanting to do this as the button.Click code is in a function that has a PropertyGrid parameter, and in the button_Click function, I need to set the PropertyGrid selected object. 我想作为按钮执行此操作。 button.Click代码位于具有PropertyGrid参数的函数中,而在button_Click函数中,我需要设置PropertyGrid所选对象。 This is only set when the button.Click button is clicked. 仅在单击button.Click按钮时设置。

If I set the tag of the button to be a PropertyGrid object, how can I retrieve this tag object in the button_Click code? 如果将按钮的标签设置为PropertyGrid对象,如何在button_Click代码中检索此标签对象?

The button_Click event is called from an object, and the sender is the object, that is not the button. 从对象调用button_Click事件,而发送者是对象,而不是按钮。

Can I please have some help with the code? 我可以在代码方面寻求帮助吗?

You cannot convince a Button that it should know anything about a PropertyGrid. 您不能说服Button它应该了解有关PropertyGrid的任何知识。 When it fires its Click event then it can only tell you about what it knows. 当它触发其Click事件时,它只能告诉您它所知道的内容。 Which is cast in stone. 这是铸在石头上的。

You trivially work around this by using a lambda expression, it can capture the PropertyGrid argument value and pass it on to the method. 您可以使用lambda表达式轻松解决此问题,它可以捕获PropertyGrid参数值并将其传递给方法。 Roughly: 大致:

    private void SubscribeClick(PropertyGrid grid) {
        button.Click += new EventHandler(
            (sender, e) => button_Click(sender, e, grid)
        );
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM