如何通过单击另一个用户控件的按钮在面板中添加用户控件? [英] How to add a User Control in a Panel from a button click of another User Control?

查看:40
本文介绍了如何通过单击另一个用户控件的按钮在面板中添加用户控件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 panel1、2 个用户控件 uc1 和 uc2.uc1 被添加到面板中.uc1 有一个按钮UC1.当我单击该按钮时,我想隐藏 uc1 并显示具有另一个按钮 UC2 的 uc2.通过单击按钮 UC2,我想隐藏 uc2 并在面板中显示 uc1.

I have a panel1, 2 user controls uc1 and uc2. uc1 is added to the panel. uc1 has a buttonUC1. When I click that button, I want to hide the uc1 and show the uc2 which has another buttonUC2. By clicking buttonUC2, I want to hide the uc2 and show uc1 in the panel.

推荐答案

虽然您可以向父窗体上的面板添加、显示或隐藏其他控件,但最好在用户控件中引发事件窗体包含单击按钮时的按钮,然后在您的表单中订阅该事件并执行您需要的操作,例如隐藏您的控件并在表单的面板上显示其他用户控件.

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.

要了解更多信息:

示例:

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();
}

不要忘记订阅表单上的 ButtonClicked 事件,使用属性网格事件选项卡或代码,或者只需双击表单上的 userControl11设计时.

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.

这篇关于如何通过单击另一个用户控件的按钮在面板中添加用户控件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆