所以我设法构建了自己的简单用户控件。基本上它是一个包含子标签控件的自定义Button。该按钮的工作方式与运行时的工作方式相同。
然而,在设计期间,每当我剪切并粘贴该按钮时,我都会遇到问题(假设我想通过剪切和粘贴将其从Panel1移动到Panel2)。
按钮本身会保留其属性,例如背景颜色等,但每次粘贴时,其中的子标签都会重新初始化,因此该标签内的文本和颜色会更改回其默认值。 标签文本的值由" Text"设置。覆盖UserControl的Text属性的属性如下:
private String _text = "Button";
[Browsable(true), Description("Sets the text displayed on the button"), Category("Display Settings")]
public override String Text {
get => _text;
set {
_text = value;
lb_Text.Text = _text;
}
}
有没有办法在Designer视图中剪切和粘贴期间保留子控件属性?
下面是为UserControl的InitializeComponent()部分生成的代码,只要将其添加到表单中,就会调用该代码。除了详细信息之外,我承认默认文本和颜色值在那里重新初始化,因此我不确定如何在剪切和粘贴期间替换它们。
private void InitializeComponent()
{
this.lb_Text = new System.Windows.Forms.Label();
this.SuspendLayout();
//
// lb_Text
//
this.lb_Text.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(127)))), ((int)(((byte)(127)))), ((int)(((byte)(127)))), ((int)(((byte)(127)))));
this.lb_Text.Dock = System.Windows.Forms.DockStyle.Fill;
this.lb_Text.Font = new System.Drawing.Font("Microsoft Sans Serif", 10F, System.Drawing.FontStyle.Bold);
this.lb_Text.ForeColor = System.Drawing.Color.Black;
this.lb_Text.Location = new System.Drawing.Point(0, 0);
this.lb_Text.Name = "lb_Text";
this.lb_Text.Size = new System.Drawing.Size(200, 50);
this.lb_Text.TabIndex = 1;
this.lb_Text.Text = "Button";
this.lb_Text.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
//
// MomentaryButton
//
this.AutoScaleDimensions = new System.Drawing.SizeF(9F, 20F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.BackgroundImage = global::HMIControls.Properties.Resources.Button_Normal;
this.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
this.Controls.Add(this.lb_Text);
this.Name = "MomentaryButton";
this.Size = new System.Drawing.Size(200, 50);
this.ResumeLayout(false);
}