【问题标题】:C# - Why is my dynamic label not transparent even if the parent is set?C# - 为什么即使设置了父级,我的动态标签也不透明?
【发布时间】:2017-09-25 01:31:22
【问题描述】:

我正在编写一个 WinForms 应用程序。在这个应用程序中,我生成动态的LabelPictureBoxTextBox 控件。

通过将 Image 拖放到 PictureBox 中,添加的 TextBox 打开。输入一些文本并按“Enter”,会触发以下方法。

        private void tb_Tile_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.KeyCode == Keys.Enter)
        {
            TextBox tb_Tile = sender as TextBox;
            Tile tb_Tag = tb_Tile.Tag as Tile;

            //add function that overgives the given name to the matrix i.e. GiveNameToMatrix()

            tb_Tile.Visible = false;

            Label lbl_Tile = Controls.Find("Label" + tb_Tag.X + tb_Tag.Y, true).FirstOrDefault() as Label;
            lbl_Tile.Visible = true;

            //find picture box by tag or sth and then make this pB the parent
            PictureBox pb_Tile = (PictureBox)gb_gridBox.Controls["Tile" + tb_Tag.X + tb_Tag.Y];
            pb_Tile.BackgroundImage = pb_Tile.Image;
            lbl_Tile.Parent = pb_Tile;
           // pb_Tile.Visible = false;
            if (pb_Tile.HasChildren)
            {
                lbl_Tile.Text = tb_Tile.Text; //parent has to be set to PictureBox
                lbl_Tile.Visible = true;
                lbl_Tile.ForeColor = Color.Black;
                lbl_Tile.BackColor = Color.Transparent;
                lbl_Tile.Location = pb_Tile.Location;

                lbl_Tile.Refresh();
                pb_Tile.Refresh();

                gb_gridBox.Controls.Add(lbl_Tile);
                lbl_Tile.BringToFront();
            }
        }
    }

我希望Label.Text 显示在PictureBox 上。这就是我将PictureBox 设置为Label 的父级并将Label.BackColor 设置为透明的原因。但是Label 只是消失在PictureBox 后面...

有没有人知道如何解决这个问题,或者可以给我一个提示,让我知道在 PictureBox 前面显示文本的另一种可能性?

提前致谢。

【问题讨论】:

  • 您是否尝试过调整控件'z-order?例如。 lbl_Tile.BringToFront();
  • 你试过设置gb_gridBox.Controls.SetChildIndex(lbl_tile, 0);吗?
  • 谢谢!是的,正如您在最后一行中看到的那样,我使用了 BringToFront()。并且设置子索引会将标签带到 PictureBox 的前面,但它不会变成透明的。

标签: c# .net winforms dynamic controls


【解决方案1】:

我看到的问题在这里:

lbl_Tile.Location = pb_Tile.Location;

Location 属性的文档:

获取或设置控件左上角相对于其容器左上角的坐标

在您的情况下,pb_Tilelbl_Tile容器,因此要获得所需的位置,您应该使用类似

lbl_Tile.Location = new Point(0, 0);

你也应该删除这一行

gb_gridBox.Controls.Add(lbl_Tile);

因为它改变了标签的Parentparent.Controls.Add(child)child.Parent = parent 做同样的事情。

【讨论】:

  • 不错,我没注意到
  • new Point(0, 0); 我的标签正在移动到gb_gridBox Groupbox 的 0,0 坐标:-/ 所以 groupbox 似乎仍然是容器
  • 它不应该,因为你这样做lbl_Tile.Parent = pb_Tile;。糟糕,您应该删除此行 gb_gridBox.Controls.Add(lbl_Tile);,因为它再次更改了 Parent
  • 好的,但是我该如何添加lbl_Tile呢?
  • 查看更新。您不需要添加它,因为设置 Parent 属性会将其添加到 Parent.Controls 集合中。在你的情况下,pb_Tile.Controls.
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-02-03
  • 1970-01-01
  • 2016-02-16
  • 2010-12-25
  • 1970-01-01
  • 1970-01-01
  • 2023-03-21
相关资源
最近更新 更多