Reputation: 28586
Situation: alt text http://lh4.ggpht.com/_1TPOP7DzY1E/S-1xy6gvB0I/AAAAAAAADNc/RRH5DpGnics/s800/Capture1.png
In A form I have a TableLayoutPanel(Dock= Fill) and a label (which parent is the Form, not the tablelayoutPanel) which anchors are set to Top+Bottom+Left+Right.
Now, when I run this form and rezise it, the label does not center itself in the Form, as I expected.
Workarounds?
Upvotes: 2
Views: 3265
Reputation: 68506
Setting anchors on more than 1 corner will try resize the label unless you only set 1 corner to anchor to.
If you set AutoSize
to false
and change the TextAlign
to MiddleCenter
on the label, the text will stay centered, but this may be undesirable as the labels dimensions would change.
The workaround is to capture the Resize
event of the Form
and set the location of the Label manually (not tested). This will mean you don't need to set AutoSize
to false and you won't need to set the anchors.
void OnResize(object sender, EventArgs e)
{
Point pos = new Point((this.Width/2) - (Label.Width / 2),
(this.Height/2) - (Label.Height/2));
Label.Location = pos;
}
Upvotes: 3
Reputation: 128387
Setting the Anchor
property causes the control to attempt to keep a constant distance from the specified edges. So if you shrink the form, the label will still maintain its distance from Top
and Left
and should therefore not remain centered.
I actually think that if you want the label to stay centered, you should set its Anchor
property to None
, not to Top, Bottom, Left, Right
.
Now, if you are going to be changing the text of the label, here's a compromise:
Anchor
property to None
. This will keep it centered.AutoSize
property to false
. This will allow you to specify a constant size.TextAlign
property of your label to MiddleCenter
.In effect, what this gives you is a rectangle that is always centered in your form, inside of which is some text consistently centered within that rectangle.
Upvotes: 1
Reputation: 28617
The trick is to have no anchors on the label. Since an anchor will try and maintain distance from the edge your setup will cause the label to grow with the form. Unfortunately this will conflict with the AutoSize setting which will want to keep the label the same size.
By having no anchors the label is free to move rather than resize and it will remain proportionally the correct distance from the forms edges.
Upvotes: 2
Reputation: 4848
I don't think it will center itself at all. When you resize a form, only the right and bottom will move, so if you have your anchor on all 4 sides, then just the right and bottom portions of the label (or any control) will follow, and leave the left and top alone.
Upvotes: 0
Reputation: 613
You have the label autosize set to true - I'm pretty sure that's what's causing the problem.
change it to false.
Upvotes: 2