我在下面附有一个示例,说明我想用我的代码完成哪些工作。如果可能的话,有人可以写一个片段或解释它如何工作?我尝试了几种不同的方法,但都没有成功(我不断收到范围错误或用户控件无法识别)。
当前试图获取UserControl1.Button1来切换UserControl2上的可见性状态。
层次结构:
我可以得到如下所示的变种,但是从usercontrol到usercontrol似乎需要一些额外的步骤。救命!
private void button1_Click(object sender, EventArgs e)
{
this.Hide();
}
private void HIDE2_Click(object sender, EventArgs e)
{
userControl21.Hide();
}
正如@ hans-passant指出的那样。
事件的使用为我们提供了一种使用观察者模式的简便方法。
当单击隐藏第二个控件的按钮时,实现一个自定义Event
InUserControl1
并调用此事件(通知观察者有关更改):
public partial class UserControl1 : UserControl
{
public event EventHandler HideRequested;
...
private void button1_Click(object sender, EventArgs e)
{
if (HideRequested != null)
{
HideRequested.Invoke(this, EventArgs.Empty);
}
}
}
在Form1中,通过实现事件处理程序将事件附加到事件:
public Form1()
{
InitializeComponent();
userControl11.HideRequested += userControl11_HideRequested;
}
void userControl11_HideRequested(object sender, EventArgs e)
{
userControl21.Hide();
}
当然,还有其他方法可以实现此目的,但是任何其他方法都可能会在代码中引入耦合。例如,这也是有效的(通过将用户控件2的访问修饰符更改为public):
private void button1_Click(object sender, EventArgs e)
{
(Parent as Form1).userControl21.Hide();
}
您还可以想到这样的事情:(那么您不必将USerControl2的访问修饰符更改为public)
在Form1中:
public void HideUserControl2()
{
userControl21.Hide();
}
并在UserControl1 button_click中:
private void button1_Click(object sender, EventArgs e)
{
(Parent as Form1).HideUserControl2();
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句