子窗体文本框事件处理程序上的父窗体方法
本文关键字:窗体 方法 程序上 事件处理 文本 | 更新日期: 2023-09-27 18:36:51
我有100个文本框,分布在20个表单中,它们都在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
}
有没有办法在每个子窗体文本框中访问父窗体的属性编辑值方法编辑值已更改
this.line1TextEditSubscriber.EditValueChanged += new System.EventHandler(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();
}
}
这允许子类将事件"传递给"父类,以便它可以处理事件,而无需子类知道使用它的类型实现的任何信息。 这个子窗体现在可以由任意数量的不同类型的父窗体使用,也可以在父窗体的特定实现全部固定/已知之前编写(允许开发人员独立处理每个窗体),并且意味着子窗体不会因对父窗体的更改而被"破坏"。 这方面的技术术语是减少耦合。
只需将其公开,然后将父窗体的实例传递给子窗体
public void PropertyEditValue(object sender, EventArgs e)
{
//Do some action
}
甚至更简单的是,如果函数 PropertyEditValue 不使用任何类变量,你可以static
声明它并直接访问它,就像
this.line1TextEditSubscriber.EditValueChanged += ParentClass.PropertyEditValue