根本不适合更改父表单中的属性。相反,您的子表单应该引发父表单侦听的事件,并相应地更改其自身的值。
从子窗体操作父窗体会产生双向耦合 - 父窗体拥有子窗体,但子窗体也对父窗体有亲密的了解和依赖。冒泡是解决此问题的既定解决方案,因为它允许信息向上流动(“冒泡”),同时避免任何严格的耦合。
这是事件处理的最基本示例。它不包括在事件中传递特定信息(这是您可能需要的),但涵盖了这个概念。
在您的孩子形式中:
//the event
public event EventHandler SomethingHappened;
protected virtual void OnSomethingHappened(EventArgs e)
{
//make sure we have someone subscribed to our event before we try to raise it
if(this.SomethingHappened != null)
{
this.SomethingHappened(this, e);
}
}
private void SomeMethod()
{
//call our method when we want to raise the event
OnSomethingHappened(EventArgs.Empty);
}
并以您的父母形式:
void OnInit(EventArgs e)
{
//attach a handler to the event
myChildControl.SomethingHappened += new EventHandler(HandleSomethingHappened);
}
//gets called when the control raises its event
private void HandleSomethingHappened(object sender, EventArgs e)
{
//set the properties here
}
正如我上面所说,您可能需要在您的活动中传递一些特定信息。有几种方法可以做到这一点,但最简单的一种是创建您自己的 EventArgs 类和您自己的委托。看起来您需要指定某个值是设置为 true 还是 false,所以让我们使用它:
public class BooleanValueChangedEventArgs : EventArgs
{
public bool NewValue;
public BooleanValueChangedEventArgs(bool value)
: base()
{
this.NewValue = value;
}
}
public delegate void HandleBooleanValueChange(object sender, BooleanValueChangedEventArgs e);
我们可以更改我们的事件以使用这些新签名:
public event HandleBooleanValueChange SomethingHappened;
我们传递我们的自定义 EventArgs 对象:
bool checked = //get value
OnSomethingHappened(new BooleanValueChangedEventArgs(checked));
我们相应地更改父级中的事件处理:
void OnInit(EventArgs e)
{
//attach a handler to the event
myChildControl.SomethingHappened += new HandleBooleanValueChange(HandleSomethingHappened);
}
//gets called when the control raises its event
private void HandleSomethingHappened(object sender, BooleanValueChangedEventArgs e)
{
//set the properties here
bool value = e.NewValue;
}