[英]Keeping controls centralized in a TableLayoutPanel
我开始使用C#,并试图创建一个包含许多不同控件的窗体。 为了使事情简单,我使用TableLayoutPanel
处理格式。 但是,我希望所有控件都集中在各自的单元中。 经过一番搜索后,我发现此页面表明可以执行此操作,您只需设置control.Anchor = AnchorStyles.None
,控件将位于其单元格的中心。
确实确实工作得很好,但是我现在发现了一个奇怪的行为。 我现在开始构建表单,因此它完全是空洞的,上面有一个简单的图形,下面有一个文本框。 完成后,图形将占据面板的整个第一行,所有其余控件将分布在其下方。
因此,我将简单地设置panel.SetColumnSpan(graph, 2)
(在两列的情况下)。 可以按预期工作,只是现在下面的TextBox不再集中。
这是我到目前为止的代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Windows.Forms.DataVisualization.Charting;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Form form = new Form();
form.AutoSize = true;
form.FormBorderStyle = FormBorderStyle.FixedDialog;
Chart chart = new Chart();
chart.Anchor = AnchorStyles.None;
//...
TextBox text = new TextBox();
text.Text = "A";
text.Anchor = AnchorStyles.None;
TableLayoutPanel box = new TableLayoutPanel();
box.AutoSize = true;
box.RowCount = 2;
box.ColumnCount = 2;
box.Controls.Add(chart,0,0);
box.SetColumnSpan(chart, 2);
box.Controls.Add(text,0,1);
form.Controls.Add(box);
form.ShowDialog();
}
}
}
这是带有box.SetColumnSpan
的结果box.SetColumnSpan
注释掉了:
并启用它:
更新:使用ColumnSpan(2)设置TextBox也可以,但是在一定程度上很重要。 例如,如果我想在第二行上有两个TextBox,则希望它们每个都位于各自单元格的中心。
在这种情况下,我现在添加第二个文本框:
TextBox text2 = new TextBox();
text2.Text = "B";
text2.Anchor = AnchorStyles.None;
并将其添加到面板中:
TableLayoutPanel box = new TableLayoutPanel();
box.AutoSize = true;
box.RowCount = 2;
box.ColumnCount = 2;
box.Controls.Add(chart,0,0);
box.SetColumnSpan(chart, 2);
box.Controls.Add(text,0,1);
box.Controls.Add(text2, 1, 1);
更新:您的代码缺少列样式。 只需这样设置,就可以完成:
this.box.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 50F));
this.box.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 50F));
为了使文本框在表单(TableLayoutPanel)的中心对齐,也将列跨度也设置为2。 如果不是,则取决于文本框的大小,该文本将居中于第一列。
this.box.ColumnCount = 2;
this.box.RowCount = 2;
this.box.Controls.Add(this.chart, 0, 0);
this.box.Controls.Add(this.text, 0, 1);
this.box.SetColumnSpan(this.chart, 2);
this.text.Anchor = System.Windows.Forms.AnchorStyles.None;
给
并设置此:
this.box.SetColumnSpan(this.text, 2);
并且没有文本列跨度,但是有文本框:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.