I have a TableLayoutPanel which takes up the whole area that is in, dock fill. I have created a 3 by开发者_JAVA百科 3 table/grid. I want to set the height and width of the middle cell and then let everything else be auto size. This way the content in the middle cell is in the center of the container.
It looks like I am going about this the wrong way. What is the best way to center content in a container(panel)?
Set first and last column as well as first and last rows in Percent
mode and the middle column and row as Autosize
.
This will make the center cell always center and adapt to its content size.
Here is some code to set the table manually:
tableLayout.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 50.0f));
tableLayout.ColumnStyles.Add(new ColumnStyle(SizeType.AutoSize));
tableLayout.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 50.0f));
tableLayout.RowStyles.Add(new RowStyle(SizeType.Percent, 50.0f));
tableLayout.RowStyles.Add(new RowStyle(SizeType.AutoSize));
tableLayout.RowStyles.Add(new RowStyle(SizeType.Percent, 50.0f));
Using the designer, set the center row and column to Absolute, the rest to 50 Percent.
Try this:
In the top right of the TableLayoutPanel, there's an arrow. Click it, and go to "Edit Rows and Columns...". Specify the middle row and middle column dimensions (in percentages or absolute pixels).
Try simply placing the content in the center of the parent container, then switching off all anchoring (the default top and left ones, specifically). It should essentially be centered now.
If you need to center control then you don't have to use TableLayoutPanel. Just add control to panel, center it manually in designer and remove all anchors.
There is similiar thread already: Centering controls within a form in .NET (Winforms)?
精彩评论