当我将标签的 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);