【问题标题】:Label not visible above ToolStrip标签在 ToolStrip 上方不可见
【发布时间】:2023-03-24 17:00:02
【问题描述】:

在运行时,我根据需要向主窗口添加(和删除)几个控件,在 Designer 中该主窗口仅包含带有一些功能按钮的 ToolStrip。在某些情况下,我想在 toolStrip 旁边添加一个信息标签,但我无法使其可见,即。它隐藏在下面。标签的代码很简单

infoLabel = new Label();
infoLabel.AutoSize = true;
infoLabel.Location = new System.Drawing.Point(200, 10);
infoLabel.Size = new System.Drawing.Size(35, 13);
infoLabel.BackColor = System.Drawing.SystemColors.Control;
infoLabel.Font = new System.Drawing.Font("Arial", 13);
infoLabel.ForeColor = System.Drawing.Color.Black;
infoLabel.TabIndex = 1;
infoLabel.Text = "this is info";
infoLabel.BringToFront();
this.Controls.Add(infoLabel);

TabIndexBringToFront 我添加了作为绝望的行为,它没有帮助。顺便说一句,ToolStrip 的 TabIndex 是 2,而它的 BackColor 我改为透明的。

但是,当我在设计器中的 ToolStrip 上放置标签时,它是可见的(即在顶部)。然后我分析了代码,但没有发现与我正在编写的内容有任何不同。我在这里错过了什么?

【问题讨论】:

  • infoLabel.BringToFront(); 之后 this.Controls.Add(infoLabel);?我们首先将infoLabel 添加到this 上,然后使infoLabel 成为topmost
  • 是的,当控件尚未添加到其父级时,BringToFront() 无法执行任何操作。什么都不能摆在面前。例外会很有用。
  • 是的,它有效!非常感谢

标签: c# winforms z-order


【解决方案1】:

我建议在最后调用infoLabel.BringToFront();,至少在之后this.Controls.Add(infoLabel);您当前的代码已修改:

infoLabel = new Label();
...
infoLabel.Text = "this is info";

// First Add to this
this.Controls.Add(infoLabel);

// Only then we can make infoLabel be the topmost 
// among all existing controls which are on this
infoLabel.BringToFront();

我们创建infoLabel,将其添加到this,最后使其置顶this。为了使代码更具可读性,我建议如下:

// Create a label on this
infoLabel = new Label() {
  AutoSize  = true,
  Location  = new System.Drawing.Point(200, 10),
  Size      = new System.Drawing.Size(35, 13),
  BackColor = System.Drawing.SystemColors.Control,
  Font      = new System.Drawing.Font("Arial", 13),
  ForeColor = System.Drawing.Color.Black,
  TabIndex  = 1,
  Text      = "this is info",
  Parent    = this // <- instead of this.Controls.Add(infoLabel);
};

// make infoLabel topmost among all controls on this
infoLabel.BringToFront();

【讨论】:

    【解决方案2】:

    Windows 窗体控件没有可用于设置控件 z-index 的属性,就像在 CSS 中所做的那样。

    您需要致电Parent.SetChildIndex(control, 0);Controls 集合前面的控件是容器控件的 z 顺序最顶端的控件。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-01-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-02
      相关资源
      最近更新 更多