ToolStrip上方的标签不可见

3

运行时,我会根据需要向一个仅包含一些功能按钮的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上方时,它是可见的(即在顶部)。我分析了代码,但没有看到任何不同于我所写的东西。我在这里错过了什么吗?


1
this.Controls.Add(infoLabel) 之后,使用 infoLabel.BringToFront() 吗?我们首先将 infoLabel 添加到 this 上,然后使 infoLabel 成为最顶层的。 - Dmitry Bychenko
1
是的,当控件尚未添加到其父级时,BringToFront() 无法执行任何操作。它还没有任何东西可以在前面。抛出异常会很有用。 - Hans Passant
是的,它有效!非常感谢。 - Marek Praski
2个回答

3

我建议在最后调用 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中,最后将其设置为最顶层。为了使代码更易读,我建议像这样编写:
// 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();

0

Windows Forms控件没有像CSS中可以设置控件z-index的属性。

您需要调用Parent.SetChildIndex(control, 0);。在容器控件中,Controls集合中最前面的控件是z-order中最高的控件。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接