通过位于另一个用户控件中的按钮将用户控件置于前面 [英] Bringing front a user control by a button which is located in another user control

查看:27
本文介绍了通过位于另一个用户控件中的按钮将用户控件置于前面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个场景(Windows 窗体、C#、.NET):

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

  1. 有一个主窗体,其中包含 2 个名为 us1us2 的用户控件.
  2. us1 里面有一个名为 btnDisplay 的按钮.
  3. 只有 us1 是可见的,因为我把它放在了前面.
  4. 当用户点击 btnDisplay 时,us2 必须出现在前面,但我在 us1 中没有对 us2 的任何控制.cs!
  1. There is a main form which hosts 2 user controls named us1 and us2.
  2. There is a button called btnDisplayinside 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!

我应该如何实施?

推荐答案

我会考虑两种选择.

1) 第一个选项是将 btnDisplay 的修饰符更改为 internalpublic 而不是 private.

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

这允许您订阅表单中的点击事件.当点击事件被触发时,您只需将另一个控件放在最前面.

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) 另一种选择是将您的 us2 控件传递给 us1 控件,以便 us1 控件可以将 us2 带到前面.

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

在你的表单中设置 us1 上的 us2 属性:

In your form set the us2 property on us1:

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

        us11.us2 = us21;
    }

}

如果让我们 1了解"另一个控件有意义,我可能会选择选项 2.如果让表单知道正在单击的按钮,然后执行某些操作更有意义,那么选项 1 可能会更好.

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.

这篇关于通过位于另一个用户控件中的按钮将用户控件置于前面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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