我正在学习 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!"));
}
}