[英]Parent form method on child forms textbox event handler
我喜欢以20种形式散布的100个文本框,它们在EditValueChanged上都做相同的事情。 这些是DevExpress.XtraEditors.TextEdit控件
ParentForm
ChildForm1
TextBox1
this.line1TextEditSubscriber.EditValueChanged += new System.EventHandler(PropertyEditValue);
TextBox2
this.line1TextEditSubscriber.EditValueChanged += new System.EventHandler(PropertyEditValue);
TextBox3
this.line1TextEditSubscriber.EditValueChanged += new System.EventHandler(PropertyEditValue);
DropDow1
ChildForm2
TextBox1
this.line1TextEditSubscriber.EditValueChanged += new System.EventHandler(PropertyEditValue);
TextBox2
this.line1TextEditSubscriber.EditValueChanged += new System.EventHandler(PropertyEditValue);
TextBox3
this.line1TextEditSubscriber.EditValueChanged += new System.EventHandler(PropertyEditValue);
DropDow1
public delegate void PropertyChangedEventHandler(object sender, EventArgs e);
//This one method is declared on the Parent Form.
private void PropertyEditValue(object sender, EventArgs e)
{
//Do some action
}
有没有一种方法可以在每个ChildForms文本框EditValueChanged中访问父窗体的PropertyEditValue方法
this.line1TextEditSubscriber.EditValueChanged += new System.EventHandler(PropertyEditValue);
只需将其公开,然后将父表单的实例传递给子表单
public void PropertyEditValue(object sender, EventArgs e)
{
//Do some action
}
甚至更简单,如果函数PropertyEditValue不使用任何类变量,则可以将其声明为static
并像直接访问它一样
this.line1TextEditSubscriber.EditValueChanged += ParentClass.PropertyEditValue
您可以做的是,在编辑每个子窗体的任何文本框时,触发每个子窗体各自的事件:
public class ChildForm2 : Form
{
private TextBox texbox1;
public event EventHandler TextboxEdited;
private void OnTextboxEdited(object sender, EventArgs args)
{
if (TextboxEdited != null)
TextboxEdited(sender, args);
}
public ChildForm2()
{
texbox1.TextChanged += OnTextboxEdited;
}
}
您还可以将所有文本框放入集合中,以便可以循环添加处理程序,而不必将该行编写20次:
var textboxes = new [] { textbox1, textbox2, textbox3};
foreach(var textbox in textboxes)
texbox.TextChanged += OnTextboxEdited;
然后,父表单可以从每个子表单中订阅该事件,并触发自己的事件:
public class ParentForm : Form
{
public void Foo()
{
ChildForm2 child = new ChildForm2();
child.TextboxEdited += PropertyEditValue;
child.Show();
}
}
这允许子类将事件“向上传递”给父类,以便它可以处理事件,而子类无需了解有关使用它的类型的实现的任何信息。 现在,该子级可以被任意数量的不同类型的父级使用,或者可以在父级的特定实现全部固定/已知(允许开发人员独立处理每种表单)之前编写该子级,这意味着该子级赢得了不会因为父项的更改而“中断”。 为此的技术术语是减少耦合。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.