[英]How to add a User Control in a Panel from a button click of another User Control?
I have a panel1, 2 user controls uc1 and uc2. 我有一个panel1,2个用户控件uc1和uc2。 uc1 is added to the panel.
uc1已添加到面板中。 uc1 has a buttonUC1.
uc1有一个按钮UC1。 When I click that button, I want to hide the uc1 and show the uc2 which has another buttonUC2.
当我单击该按钮时,我想隐藏uc1并显示具有另一个按钮UC2的uc2。 By clicking buttonUC2, I want to hide the uc2 and show uc1 in the panel.
通过单击buttonUC2,我想隐藏uc2并在面板中显示uc1。
While you can add, show or hide the other control to a panel on the parent form, but instead, it's better to raise an event form the user control that contains the button when the button clicked, then subscribe for that event in your form and do what you need, for example hide your control and show the other user control on the panel on your form. 尽管您可以在父窗体的面板上添加,显示或隐藏其他控件,但是相反,最好是在单击该按钮时从包含该按钮的用户控件中引发一个事件,然后在窗体中订阅该事件并执行所需的操作,例如隐藏控件并在窗体的面板上显示其他用户控件。
To learn more: 了解更多:
Example: 例:
The code for UserControl1
: 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);
}
}
And then use the event in your form: 然后以您的形式使用该事件:
private void userControl11_ButtonClicked(object sender, EventArgs e)
{
MessageBox.Show("Button of UserControl1 Clicked!");
//or for example, userControl11.Hide(); userControl21.Show();
}
Don't forget to subscribe for ButtonClicked
event on your form, using property grid event tab, or code or simply by double click on your userControl11
on your form at design-time. 不要忘记使用属性网格事件选项卡或代码或在设计时双击表单上的
userControl11
来订阅ButtonClicked
上的ButtonClicked
事件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.