获取按钮所属的对象? [英] Get what object a button belongs to?
问题描述
我会尽力缩短这个问题。如果我有以下课程:
I will try to shorten this question. If I have the following class:
public class MyClass<br />{<br />public int MyInt {get; set;}<br />public Button MyBtn {get; set;}<br />}
现在,假设我有一个for循环,它生成了这个类的几个对象,并将它连接到这样的事件处理程序:
Now, let's say I have a for-loop that generates several objects of this class and hooks it up to an event handler like this:
for (int i = 0; i < 5; i++)<br /> {<br /> MyClass myClass = new MyClass();<br /> myClass.MyInt = i;<br /> myClass.MyBtn = new Button();<br /> myClass.MyBtn.Click += (s, e) =><br /> {<br /> //Is it possible to get the value of 'myClass.MyInt'<br /> //in this event handler since 'myClass.MyBtn' belongs<br /> //to the same object?<br /> };<br /> }
所以,我的问题是:单击按钮时是否可以获取'myClass.MyInt'的值?我的意思是,'myClass.MyBtn'和'myClass.MyInt'属于同一个对象。问题是我必须将所有按钮连接到同一个事件处理程序。
感谢您的帮助!
So, my question is: Is it possible to get the value of 'myClass.MyInt' when the button is clicked? I mean, 'myClass.MyBtn' and 'myClass.MyInt' belongs to the same object. The problem is that I must hook up all buttons to the same event handler.
Thanks for help!
推荐答案
您甚至不需要额外的类,您可以使用myClass.MyBtn.Tag = myClass;
将MyClass引用存储在Button中,以便稍后事件处理程序可以将其发送者转换为Button转换为MyClass实例。 br>
:)
You don't even need an extra class, you could store the MyClass reference inside the Button usingmyClass.MyBtn.Tag=myClass;
so later an event handler could convert its sender to Button to MyClass instance.
:)
嗯,是的,但有点奇怪:
Well, yes, but it's kind of weird:
private void Form1_Load(object sender, EventArgs e)
{
for (int i = 0; i < 5; i++)
{
Button newButton = new Button
{
Text = "Button: " + i.ToString(),
Location = new Point(i*80 + 50, 50),
BackColor = Color.AliceBlue
};
MyClass myClass = new MyClass();
myClass.MyInt = i;
myClass.MyBtn = newButton;
myClass.MyBtn.Click += (s, earg) =>
{
MyClass myclass = s as MyClass;
MessageBox.Show(myClass.MyInt.ToString());
};
this.Controls.Add(newButton);
}
}
如果你描述了你想要达到的目标,我或许可以提出一个更好的方法。
If you describe what you are trying to achieve, I may be able to suggest a better way.
这篇关于获取按钮所属的对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!