我正在学习C#,作为书中练习的一部分,我必须在表格中居中标签。表单是否相当大小并不重要。我在这里找到了 - 在stackoverflow上 - 以及其他一些地方不同的解决方案,我把它缩小到两个。但似乎,虽然非常受欢迎的解决方案,但它们不会产生相同的结果。
看起来像那样 方法1
myLabel.Left = (this.ClientSize.Width - myLabel.Width) / 2;
myLabel.Top = (this.ClientSize.Height - myLabel.Height) / 2;
将产生以左侧为中心的标签,并向上偏离中心,并且 方法2
myLabel2.Dock = DockStyle.Fill;
myLabel2.TextAlign = ContentAlignment.MiddleCenter;
将使其在形式中间完美对齐。
现在,我的问题是为什么存在差异,换句话说,为什么方法1中存在左侧偏移??
整个代码如下:
//Exercise 16.1
//-------------------
using System.Drawing;
using System.Windows.Forms;
public class frmApp : Form
{
public frmApp(string str)
{
InitializeComponent(str);
}
private void InitializeComponent(string str)
{
this.BackColor = Color.LightGray;
this.Text = str;
//this.FormBorderStyle = FormBorderStyle.Sizable;
this.FormBorderStyle = FormBorderStyle.FixedSingle;
this.StartPosition = FormStartPosition.CenterScreen;
Label myLabel = new Label();
myLabel.Text = str;
myLabel.ForeColor = Color.Red;
myLabel.AutoSize = true;
myLabel.Left = (this.ClientSize.Width - myLabel.Width) / 2;
myLabel.Top = (this.ClientSize.Height - myLabel.Height) / 2;
Label myLabel2 = new Label();
myLabel2.Text = str;
myLabel2.ForeColor = Color.Blue;
myLabel2.AutoSize = false;
myLabel2.Dock = DockStyle.Fill;
myLabel2.TextAlign = ContentAlignment.MiddleCenter;
this.Controls.Add(myLabel);
this.Controls.Add(myLabel2);
}
public static void Main()
{
Application.Run(new frmApp("Hello World!"));
}
}
答案 0 :(得分:4)
这种情况正在发生,因为您在将标签添加到表单的控件之前使用了标签的宽度。
但是,自动标签的宽度是在添加到控件列表后计算的。在此之前,如果您查看宽度,它将是一些固定的默认值,例如100。
您可以通过重新排列代码来修复它,以便在将标签添加到表单控件后调整标签的位置。
private void InitializeComponent(string str)
{
this.BackColor = Color.LightGray;
this.Text = str;
//this.FormBorderStyle = FormBorderStyle.Sizable;
this.FormBorderStyle = FormBorderStyle.FixedSingle;
this.StartPosition = FormStartPosition.CenterScreen;
Label myLabel = new Label();
myLabel.Text = str;
myLabel.ForeColor = Color.Red;
myLabel.AutoSize = true;
Label myLabel2 = new Label();
myLabel2.Text = str;
myLabel2.ForeColor = Color.Blue;
myLabel2.AutoSize = false;
myLabel2.Dock = DockStyle.Fill;
myLabel2.TextAlign = ContentAlignment.MiddleCenter;
this.Controls.Add(myLabel);
this.Controls.Add(myLabel2);
myLabel.Left = (this.ClientSize.Width - myLabel.Width) / 2;
myLabel.Top = (this.ClientSize.Height - myLabel.Height) / 2;
}