简体   繁体   English

在用户控件中显示/隐藏面板 Form1

[英]Show/Hide Panel Form1 in Usercontrol

Anyone know how can I hide/show panel of Form1 but my button is in UserControl , I want to add button in UserControl to hide and show panel of Form1 .任何人都知道如何隐藏/显示Form1的面板,但我的按钮在UserControl中,我想在UserControl中添加按钮来隐藏和显示Form1的面板。 How can i do that?我怎样才能做到这一点?

Here's my code for hide and show:这是我的隐藏和显示代码:

private void button3_Click_1(object sender, EventArgs e)
{
    flag *= -1;
    if (flag == 1)
        bunifuGradientPanel1.Hide();
    else
        bunifuGradientPanel1.Show();
}

Controls should not know about their containers explicitly, in order to maintain loose coupling.为了保持松散耦合,控件不应该明确知道它们的容器。 Any control can call its FindForm method to get a reference to its form of type Form .任何控件都可以调用它的FindForm方法来获取对其类型Form的引用。 That should only be used to do general form things though.不过,那应该只用于做一般形式的事情。 A child control should not know that its parent form is a specific type, never mind what that type contains.子控件不应该知道其父窗体是特定类型,更不用说该类型包含什么。

The proper way to do this is for the user control to raise an event.执行此操作的正确方法是让用户控件引发事件。 That event can notify any listeners that something has happened and those listeners can then do whatever is required.该事件可以通知任何听众发生了什么事,然后这些听众可以做任何需要的事情。 In this case, the form would handle the event of the user control and then hide its own Panel .在这种情况下,表单将处理用户控件的事件,然后隐藏自己的Panel

The user control might contain code like this:用户控件可能包含如下代码:

public event EventHandler Button1Click;

protected void OnButton1Click(EventArgs e)
{
    Button1Click?.Invoke(this, e);
}

private void button1_Click(object sender, EventArgs e)
{
    OnButton1Click(EventArgs.Empty);
}

For more information on raising your own events, see here .有关发起您自己的事件的更多信息,请参见此处

When the user clicks button1 on the user control, that user control will raise its Button1Click event.当用户单击用户控件上的button1时,该用户控件将引发其Button1Click事件。 The form containing the user control can then handle that event and do whatever is required, just as it could handle the Click event of a regular Button and do whatever is required, eg然后,包含用户控件的表单可以处理该事件并执行所需的任何操作,就像它可以处理常规ButtonClick事件并执行所需的任何操作一样,例如

private void someUserControl1_Button1Click(object sender, EventArgs e)
{
    panel1.Visible = !panel1.Visible;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM