如何在control1或form1中从class2触发事件? [英] How do I fire event from class2 in either control1 or form1 ?
问题描述
我有Class2,Form1和Control1。
I have Class2, Form1 and Control1.
class Class2
{
public int number = 0;
public string name = "X";
public event EventHandler DataAvailable;
public void OnDataAvailable(EventArgs e)
{
if (DataAvailable != null) DataAvailable(this, e);
}
}
1-当我按下Control1中的按钮时,我更新'在Class2中的数字'。
2-当我按下Form1中的按钮时,我在Class2中更新'number'。
3-每次从任一控件(Form1或Control1)按下按钮时,都会触发Class2中的事件。并且正在两个控件中更新label1,并且来自任一控件的label1显示来自Class2的数字。
清除为泥浆?
如何我可以这样做吗?由于Class2必须是Form1或Control1中的对象,但不能同时是两者,因为它将是2个对象。另外,没有使Class2静止。
谢谢。
我尝试过:
a自2005年以来很多东西......................... .........
1- When I press a button in Control1, i update 'number' in Class2.
2- When I press a button in Form1, i update 'number' in Class2.
3- The event from Class2 is fired every time when a button is pressed from either controls(Form1 or Control1) ; and is updating label1, also in both controls, and label1 from either controls is showing number from Class2.
Clear as mud?
How can I do this? Since Class2 must be an object in Form1 OR Control1, but not both since it will be 2 objects. Also, without making Class2 static.
Thank you.
What I have tried:
a lot of stuff since 2005..................................
推荐答案
您可以在Class2中创建一个公共方法来触发事件,并从其他位置调用它。
或者将数字设为一个属性 - 无论如何,公共字段通常是一个坏主意 - 并且在设置器中更改时即可触发。
但说实话,这听起来像是你到达那里的屁股倒退设计。
You can create a public method in Class2 which fires the event, and call it from the other locations.
Or make number a property - which it should be anyway, public fields is generally a bad idea - and fire the even when it is changed in the setter.
But to be honest, that does sound like an ass-backwards design you got there.
这篇关于如何在control1或form1中从class2触发事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!