简体   繁体   中英

Bringing front a user control by a button which is located in another user control

I have a scenario (Windows Forms, C#, .NET):

  1. There is a main form which hosts 2 user controls named us1 and us2 .
  2. There is a button called btnDisplay inside us1 .
  3. Only us1 is visible, because I have brought it to front.
  4. When user clicks on btnDisplay , us2 must come to front but I don't have any controls on us2 inside us1.cs !

How should I implement this?

There are two options I'd consider.

1) The first option would be to change the modifier of btnDisplay to be internal or public instead of private .

更改btnDisplay修饰符

This allows you to subscribe to the click event in your form. When the click event is fired you simply bring the other control to the front.

public Form1()
{
  InitializeComponent();

  us11.btnDisplay.Click += BtnDisplay_Click;
}

private void us11_DisplayButtonClicked(object sender, EventArgs e)
{
  us21.BringToFront();
}

2) The other option would be to pass your us2 control to the us1 control so the us1 control can bring us2 to the front.

public partial class us1 : UserControl
{
    // Property to hold the us2 control.
    public us2 us2 { get; set; }

    public us1()
    {
        InitializeComponent();
    }

    private void btnDisplay_Click(object sender, EventArgs e)
    {
        // Bring the other control to the front if the property has been set.
        us2?.BringToFront();
    }
}

In your form set the us2 property on us1:

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();

        us11.us2 = us21;
    }

}

I'd probably go with option 2 if it makes sense for us1 to "know" about the other control. If it makes more sense for the form to know about the button being clicked, and then to do something, then option 1 might be better.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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