简体   繁体   English

通过位于另一个用户控件中的按钮将用户控件置于前面

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

I have a scenario (Windows Forms, C#, .NET): 我有一个场景(Windows窗体,C#、. NET):

  1. There is a main form which hosts 2 user controls named us1 and us2 . 有哪些主机2所指定的用户控制的主形式us1us2
  2. There is a button called btnDisplay inside us1 . 有一个叫按钮btnDisplayus1
  3. Only us1 is visible, because I have brought it to front. 只有us1是可见的,因为我已经将它放在前面。
  4. When user clicks on btnDisplay , us2 must come to front but I don't have any controls on us2 inside us1.cs ! 当用户点击btnDisplayus2必须走到前面,但我没有任何控制us2us1.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 . 1)第一种选择是将btnDisplay的修饰符更改为internalpublic而不是private

更改btnDisplay修饰符

This allows you to subscribe to the click event in your form. 这使您可以订阅表单中的click事件。 When the click event is fired you simply bring the other control to the front. 当触发click事件时,您只需将另一个控件置于最前面即可。

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. 2)另一个选择是将您的us2控件传递给us1控件,以便us1控件可以将us2置于最前面。

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: 在您的表单中,在us1上设置us2属性:

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. 如果对我们来说“知道”另一个控件有意义,那么我可能会选择选项2。 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. 如果让表单了解单击的按钮,然后再执行某项操作更有意义,则选项1可能更好。

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

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