4

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

1 回答 1

6

发生这种情况是因为您在将标签添加到表单控件之前使用了标签的宽度。

但是,自动调整大小的标签的宽度是在将其添加到控件列表之后计算的。在此之前,如果您查看宽度,它将是一些固定的默认值,例如 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;
}
于 2013-04-29T12:52:51.600 回答