开发平台为vs2008 模拟器为mobile 5.0
在开发过程中我遇到过这样的问题,就是如何用程序关闭用户自定义控件所在的窗体。
程序要实现的功能简化描述为:在父窗体ParentForm中有个Button,点击Button后要弹出一个子窗体ChildForm,在子窗体ChildForm中有含有用户自定义控件userControl,这里我们把userControl简化为一个panel和一个button的组合体。现在要求点击userControl中的button就关闭ChildForm。
在Winform中的很容易实现,你只需要在用户自定义控件userControl1的Button_Click中写一句话this.FindForm().Close().
但是在Mobile中解决起来好像就没有这么容易了,因为你在用户自定义控件中找不到FindForm()这个方法。这时你还想实现这个关闭功能就要费点劲了。
在这里我使用自定义触发事件来实现:
首先:在userControl中定义事件,这个事件在该控件的父窗体childForm中注册。
//点击button触发关闭窗体事件。
private void button1_Click(object sender, EventArgs e)
{
RaiseCloseFormParent();
}
//定义关闭事件
public event EventHandler<EventArgs> FormClose;
//关闭窗体事件
public void RaiseCloseFormParent()
{
if (FormClose != null)
{
this.FormClose(this, new EventArgs());
}
}
public ChildForm()
{
InitializeComponent();
userControl Myuc = new userControl();
this.Controls.Add(Myuc);
Myuc.FormClose+=new EventHandler<EventArgs>(Myuc_FormClose);
}
//该函数执行窗体关闭。
private void Myuc_FormClose(object sender,EventArgs e)
{
this.Close();
}
写完了,这样就能实现如同winform中同样的功能了。