我有usercontrol
只有一个按钮
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
我正在将Usercontrol用于此mainform
我需要从这个类中获取值
在构造函数中:
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?
if(getvalue!=null)
getvalue(null, new EventArga(value));
因为我不允许这样做 classname.properties
以及不允许使用像这样的方法传递参数
在Usercontrol类中 Mainform obj = new Mainform ();
obj.getvalue(value);
还有其他办法吗?我的意思是通过使用事件将变量传递给另一个类?
答案 0 :(得分:2)
您可以创建自己的events
,然后可以从usercontrol
(此处是事件发生地点)触发它们,并在主表单上放置一个监听器。
用户控制:
//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和一个事件监听器
主要形式:
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)
}