我有一个panel1,2个用户控件uc1和uc2。 uc1被添加到面板中。 uc1有一个buttonUC1。当我单击该按钮时,我想隐藏uc1并显示另一个按钮UC2的uc2。通过单击buttonUC2,我想隐藏uc2并在面板中显示uc1。
答案 0 :(得分:0)
虽然您可以向父表单上的面板添加,显示或隐藏其他控件,但是,当按钮单击时,从包含按钮的用户控件中提升事件会更好,然后订阅对于表单中的该事件并执行您需要的操作,例如隐藏您的控件并在表单上的面板上显示其他用户控件。
了解详情:
示例:强>
UserControl1
的代码:
[System.ComponentModel.DefaultEvent("ButtonClicked")]
public partial class UserControl1 : UserControl
{
public UserControl1()
{
InitializeComponent();
button1.Click += button1_Click;
}
public event EventHandler ButtonClicked;
protected virtual void OnButtonClicked(EventArgs e)
{
var handler = ButtonClicked;
if (handler != null)
handler(this, e);
}
private void button1_Click(object sender, EventArgs e)
{
OnButtonClicked(EventArgs.Empty);
}
}
然后在表单中使用该事件:
private void userControl11_ButtonClicked(object sender, EventArgs e)
{
MessageBox.Show("Button of UserControl1 Clicked!");
//or for example, userControl11.Hide(); userControl21.Show();
}
不要忘记在您的表单上订阅ButtonClicked
活动,使用媒体网格事件标签或代码,或者只是在设计时双击您表单上的userControl11
。