如何将函数绑定到C#中控件数组中每个控件的Click事件
当您在 C# 中创建控件数组时,如何将接收单击按钮索引的函数绑定到其单击事件?
这里有一些代码只是为了更好地理解。在代码顶部的某个位置定义按钮:
Button [] buttons = new Button[100];
它们的标准 Click 事件如下所示:
private void myClick(object sender, EventArgs e)
{
}
通常您以这种方式绑定它:
for (int i = 0; i < 100; i++)
buttons[i].Click += myClick;
但我希望事件处理程序采用这种形式:
private void myClick(int Index)
{
}
应该如何我将点击事件绑定到带有/不带有临时函数的上述函数?
我考虑过使用委托、Func
表示法,或者以某种方式传递一个包含单击按钮索引的自定义 EventArgs;但由于缺乏足够的 C# 知识,我没有成功。
如果你们中的任何人建议将每个控件的索引保存在其标签中:是的,这是可能的,但由于某种原因我不想使用它,因为如果您有一个类抛出一些事件但没有标记属性什么的,这种方式没啥用。
When you create an array of controls in C#, how can you bind a function that receives the index of the clicked button to their click event?
Here's some code solely for better understanding. Somewhere on top of the code you define the buttons:
Button [] buttons = new Button[100];
The standard Click event of them looks like this:
private void myClick(object sender, EventArgs e)
{
}
And normally you bind it this way:
for (int i = 0; i < 100; i++)
buttons[i].Click += myClick;
But I want the event handler to be in this form:
private void myClick(int Index)
{
}
How should I bind click events to the above function with / without interim functions?
I thought about using delegates, Func<T, TResult>
notation, or somehow pass a custom EventArgs which contains the Index of the clicked button; but I wasn't successful due to lack of enough C# knowledge.
If any of you are going to suggest saving the index of each control in its Tag: Yes it was possible but I don't wanna use it for some reason, since if you have a class which throws some events but doesn't have a Tag property or something, this way is useless.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
正如下面的评论中所发布的,由于其作用域,使用“i”将为所有控件使用相同的变量。因此,有必要在与 lambda 表达式相同的范围内创建一个新变量。
As posted in the comment below, using 'i' will use the same variable for all controls due to it's scope. It's therefore necessary to create a new variable in the same scope as the lambda expression.