When I set a label’s ContentAlignment property to MiddleRight, I expect it to align to the right within the panel on which I place it. Instead, it stubbornly stays put aligned left. Why is this, and how can I fix it? Here’s my code:
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);
}
Everything is working EXCEPT horizontal placement. I don’t want to set the Left property, because I want certain alignments to take up all the “right side” space they can; calculating the XPos is possible, I’m sure, but also quite complicated, I’m even more sure.
UPDATE
Olivier’s answer worked just fine. The code is now:
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);
}
UPDATE 2
I had to add a tweak to the height of the label to prevent large font sizes from being chopped off at the knees, so to speak:
// 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);
TextAlignaligns the text within the label, not the label within the panel. Consider using theAnchorproperty in order to align the label to the right edge of the panel.UPDATE
Here’s how this can be done: Make the label the same width than the panel, anchor the label to the top, left and right
Now the label resizes together with the panel and the text aligns correctly within the label. Set
lbl.AutoSizetofalsein order to make the label size independent of the text length.