标签在工具条上方不可见

时间:2019-12-18 14:14:14

标签: c# winforms z-order

在运行时,我会根据需要向主窗口中添加(或删除)多个控件,该主窗口在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变成了透明。

但是,当我在Designer中的ToolStrip上放置标签时,它是可见的(即,在顶部)。然后,我分析了代码,但没有发现与我编写的内容有所不同的内容。我在这里想念什么?

2 个答案:

答案 0 :(得分:2)

我建议在通话结束时至少在之后 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上成为 top 。为了使代码更具可读性,我建议使用以下代码:

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

答案 1 :(得分:0)

Windows窗体控件不具有可用于设置控件的z-index的属性,就像在CSS中一样。

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