我想将控件发送到其容器的背面。无论从同一个容器中创建和删除其他一些控件,我都不希望这个控件失去它的位置。
我没有更好的方法来实现这一点:
// Force this control to stay back
private void panel1_ControlAdded(object sender, ControlEventArgs e)
{
pictureBox1.SendToBack();
}
这对我来说看起来有点过分了。这是实现这一目标的更好方法吗?
编辑:
有人告诉我,controls.add 默认将控件放在前面。我无法重现这种行为,或者我在某处错过了重点。这是我尝试过的:
using System;
using System.Drawing;
using System.Windows.Forms;
namespace WindowsFormsApplication4
{
public partial class Form1 : Form
{
System.Windows.Forms.Button button1;
public Form1() { InitializeComponent(); }
void InitializeComponent()
{
this.button1 = new System.Windows.Forms.Button();
this.pictureBox1 = new System.Windows.Forms.PictureBox();
((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).BeginInit();
this.SuspendLayout();
//
// button1
//
this.button1.Location = new System.Drawing.Point(225, 182);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(139, 39);
this.button1.TabIndex = 0;
this.button1.Text = "button1";
this.button1.UseVisualStyleBackColor = true;
this.button1.Click += new System.EventHandler(this.button1_Click);
//
// pictureBox1
//
this.pictureBox1.Image = global::WindowsFormsApplication4.Properties.Resources.Tulips;
this.pictureBox1.Location = new System.Drawing.Point(36, 26);
this.pictureBox1.Name = "pictureBox1";
this.pictureBox1.Size = new System.Drawing.Size(299, 175);
this.pictureBox1.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage;
this.pictureBox1.TabIndex = 1;
this.pictureBox1.TabStop = false;
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(376, 233);
this.Controls.Add(this.button1);
this.Controls.Add(this.pictureBox1);
this.Name = "Form1";
this.Text = "Form1";
this.Load += new System.EventHandler(this.Form1_Load);
((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).EndInit();
this.ResumeLayout(false);
}
private PictureBox pictureBox1;
Point xy;
// Add a button or anything else
private void button1_Click(object sender, EventArgs e)
{
var ctl = new Button();
ctl.Location = xy;
this.Controls.Add(ctl);
xy.Offset(10, 10);
}
// First of all, send the picture box to back
private void Form1_Load(object sender, EventArgs e)
{
pictureBox1.SendToBack();
}
}
}
因此,您可以注意到,当我多次点击 button1 时,新添加的按钮(可以用文本框替换...)位于已在 Load 事件中发送回的图片框后面。所以我绝对不能依赖 Control.Add 假定的默认行为。