0

当我将标签的 ContentAlignment 属性设置为 MiddleRight 时,我希望它与我放置它的面板中的右侧对齐。相反,它顽固地保持左对齐。为什么会这样,我该如何解决?这是我的代码:

private void CreateNewLabel(int YPos, string DisplayStr, ContentAlignment contentAlign,
                            int FontSize)
{
    Label lbl = new Label();
    //lbl.Left = DEFAULT_XPOS;
    lbl.Font = new Font(lbl.Font.Name, FontSize, lbl.Font.Style);
    lbl.Top = YPos;
    lbl.Text = DisplayStr;
    lbl.TextAlign = contentAlign;
    lbl.AutoSize = true;
    panelFauxLabel.Controls.Add(lbl);
}

除了水平放置外,一切都在工作。我不想设置 Left 属性,因为我希望某些对齐能够占据所有“右侧”空间;我敢肯定,计算 XPos 是可能的,但也相当复杂,我更确定。

更新

奥利维尔的回答效果很好。现在的代码是:

    private void CreateNewLabel(int YPos, string DisplayStr, ContentAlignment contentAlign, int FontSize)
    {
        Label lbl = new Label();
        lbl.Left = DEFAULT_XPOS;
        lbl.Font = new Font(lbl.Font.Name, FontSize, lbl.Font.Style);
        lbl.Top = YPos;
        lbl.Text = DisplayStr;
        lbl.TextAlign = contentAlign;
        if (contentAlign.Equals(ContentAlignment.MiddleRight))
        {
            lbl.Anchor = AnchorStyles.Right;
        }
        else // there is no AnchorStyles.Center or AnchorStyles.Middle
        {
            lbl.Anchor = AnchorStyles.Left;
        }
        lbl.AutoSize = false;
        lbl.Width = panelFauxLabel.Width;
        panelFauxLabel.Controls.Add(lbl);
    }

更新 2

我不得不对标签的高度进行调整,以防止大字体在膝盖处被截断,可以这么说:

    // This factor was just a guess, but it seems to work pretty well
    double down = Math.Round(FontSize*1.5);
    lbl.Height = Convert.ToInt32(down);
4

1 回答 1

1

TextAlign对齐标签内的文本,而不是面板内的标签。考虑使用该Anchor属性将标签与面板的右边缘对齐。


更新

这是如何做到的:使标签与面板的宽度相同,将标签锚定在顶部、左侧和右侧

lbl.TextAlign = contentAlign;
lbl.AutoSize = false;
lbl.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
lbl.Top = YPos;
lbl.Left = 0;
lbl.Width = panelFauxLabel.ClientSize.Width; // ClientSize takes account of scroll
                                             // bars, borders and padding.
panelFauxLabel.Controls.Add(lbl);

现在标签与面板一起调整大小,文本在标签内正确对齐。设置lbl.AutoSizefalse以使标签大小与文本长度无关。

于 2013-02-15T17:55:33.393 回答