这种情况经常发生:我布置了很多控件,并且出于任何原因,我决定将它们放入面板中-也许是为了更轻松地一次禁用所有控件而不影响其他控件,或者隔离一些单选按钮,等等。
我发现在控件“下方”添加System.Windows.Forms.Panel
是一项繁琐的操作。这通常涉及调整父控件或窗体的大小,因此我可以将面板添加到与控件集合相邻的临时空间中,该控件将很快占据该面板,然后将控件拖动到面板上,然后将父控件/窗体的大小设置为以前是什么。
通常,我会在各种控件上以各种方式设置 anchor ,以便在没有精心调整的控件布局弄乱所有内容的情况下,不会简单地调整父级的大小。
对于如此简单的操作而言,这显然是一个繁琐的过程。是否有VS技巧来做到这一点(除了手动编辑设计器生成的文件之外,这意味着我必须手动选择要重新父代化的控件名称)?
最佳答案
没有直接的方法,但是有一种解决方法( Visual Studio 2010-2019 ):
假设您有一个名为Form1.cs
的表单,并且上面已经有控件,例如linkLabel,checkBoxes,radioButtons和progressBar。
诀窍是编辑*.Designer.cs
文件,而不是四处移动控件。请执行下列操作:
panel1
)像通常那样(通过使用工具箱)放置在Form1
上,并为其设置大小,使其覆盖其他控件。 Form1.Designer.cs
变为可见。打开它。 //
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(284, 262);
this.Controls.Add(this.progressBar1);
this.Controls.Add(this.linkLabel1);
this.Controls.Add(this.panel1);
this.Controls.Add(this.checkBox1);
this.Controls.Add(this.radioButton1);
this.Controls.Add(this.btnOk);
this.Name = "Form1";
this.Text = "Form1";
this.panel1.ResumeLayout(false);
this.panel1.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
然后,查找创建面板的代码:
//
// panel1
//
this.panel1.Location = new System.Drawing.Point(12, 12);
this.panel1.Name = "panel1";
this.panel1.Size = new System.Drawing.Size(260, 198);
this.panel1.TabIndex = 7;
您需要做的就是将控件从表单的
Controls
集合(this.Controls
)移至面板的Controls
集合(this.panel1.Controls
)。将其从源代码中的一个位置移到另一个位置,然后使用 ALT + Shift (Visual Studio编辑器中的block edit mode-在开始选择之前按住键,并在选择整个块之后释放它们)进行替换this.Controls
通过this.panel1.Controls
:剩下的仅添加到表单中的控件是
panel1
和ok按钮btnOk
: //
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(284, 262);
this.Controls.Add(this.panel1);
this.Controls.Add(this.btnOk);
this.Name = "Form1";
this.Text = "Form1";
this.panel1.ResumeLayout(false);
this.panel1.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
最后,关闭
Form1.Designer.cs
并通过双击Form1.cs
重新打开表单。现在,您应该在面板内部看到控件。职位与以前相同。注意:此说明是为Visual Studio进行的,如果您使用的是 Visual Studio代码,则可以使用multi cursor selection来实现此目的:键盘快捷键为:Strg + Alt + Arrow Up或Strg + Alt + Arrow Down 。或者,您可以选择然后按Ctrl + Shift + L将多个光标添加到当前选择的所有实例中。使用多个光标时,您键入的任何内容都会在所有光标位置上插入/覆盖。
关于.net - 如何在现有控件下放置一个新面板?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23955908/