Right now I clarify this may b开发者_JAVA技巧e a duplicated question from: Right-aligned labels in WinForms But non of the answers satisfied me.
The problem is very simple:
I have a right aligned label with autosize set to true. The expected behavior is that when the text is increased the right coordinate remain unchanged. But that is not what it happens. The left coordinate is the one which remains unchanged.
My app is kind of small, so I don't want to start putting controls into panels and so. So I've tried all solutions that involved ONLY label properties. The only one which worked is to set autosize to false and over-size it. (Accepted solution of question Nº1692383). But it is really ugly! I'd really like to avoid that.
Any other possible solution?
One solution would be to capture the label's right margin in the form constructor, and in the label SizeChanged
event, reset the location based on the initial right margin, the label's current Width
and the label Parent's current Width
.
This also assumes the label is anchored on the right to handle form resizing.
private readonly int _rightMargin;
public Form1()
{
InitializeComponent();
_rightMargin = label1.Parent.Width - label1.Right;
}
private void label1_SizeChanged(object sender, EventArgs e)
{
label1.Location = new Point(label1.Parent.Width - _rightMargin - label1.Width, label1.Top);
}
精彩评论