如何使用事件将参数传递给另一个类 [英] How to pass a parameter to another class using events
问题描述
我有一个带有一个按钮的 usercontrol
I have a usercontrol
which is having one button
Usercontrolclass.cs
按钮点击事件
private void btn_OK_Click(object sender, EventArgs e)
{
value= Convert.ToDouble(txt_ActualValue.Text);
if(getvalue!=null)
getvalue(null, new EventArga());
}
私有变量
private int value;
属性:
public double finalvalue
{
get
{
return value;
}
}
MainForm.cs
我正在将该用户控件用于此主表单
I'm using that Usercontrol into this mainform
我需要从此类中获取价值
I need to get the value from this class
在构造函数中:
Usercontrolclass.getvalue+=Usercontrolclass_getvalue;
在方法中:
private void UserControlclass_getvalue()
{
here I need to get the "value";
int myval = Usercontrolclass.finalvalue; // I can get like this
}
我的问题是不使用属性,只是将一个参数传递给事件参数,然后将值传递给mainfrom?
my question is without using properties simply pass a parameter into the event arguments and get the value in to the mainfrom?
if(getvalue!=null)
getvalue(null, new EventArga(value));
因为我不允许这样做 classname.properties
Because I don't allowed to do like this classname.properties
以及不允许使用此类方法传递参数
as well as don't allowed to pass a parameter using method like this
在Usercontrol类中
in Usercontrol class
Mainform obj = new Mainform ();
obj.getvalue(value);
还有其他方法可以做到吗?我的意思是通过使用事件将变量传递给另一个类?
Is there any other way to do this? I mean pass a variable to another class by using events?
推荐答案
您可以创建自己的事件
,也可以从 usercontrol
触发它们(在此处事件发生),然后在您的主表单上放置一个侦听器.
You can make your own events
, you can fire them from the usercontrol
(here is where the event takes place) and put a listener on your main form.
用户控制:
//You custom event, has to be inside namespace but outside class
public delegate void MyCustomEvent(int value);
public partial class aUserControl : UserControl
{
//Here you initialize it
public event MyCustomEvent CustomEvent;
public aUserControl()
{
InitializeComponent();
}
private void theButton_Click( object sender, EventArgs e )
{
CustomEvent?.Invoke(5);//using magic number for test
//You can call this anywhere in the user control to fire the event
}
}
现在在主要形式中,我添加了usercontrol和一个事件侦听器
Now in the main form I added the usercontrol and an event listener
主要形式:
public Form1()
{
InitializeComponent();
//Here you add the event listener to your user control
aUserControl1.CustomEvent += AUserControl1_CustomEvent;
}
private void AUserControl1_CustomEvent( int value )
{
MessageBox.Show(value.ToString());
//This is the Main form and I now have the value here
//whenever the button is clicked (or event is fired from somewhere else)
}
这篇关于如何使用事件将参数传递给另一个类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!