How can I link a component's Size to the Window size?

陌路散爱 提交于 2019-12-31 03:54:11

问题


I am making a simple WinForms program.
I would like to link a component's size to the size of the Window.

Let's say the user enlarges or shrinks the Window by dragging it's borders: I would like that a component gets bigger when the Window does and vice versa.

Let's pretend that we have two Buttons, in the center of the Window, side by side: I want to make them the same size filling the entire width of the Window.

How can I do that?


回答1:


Sample procedure, using a TableLayoutPanel and 2 Buttons:

  • Add a TableLayoutPanel to the Form
    1. Edit the Columns and Rows collections so that you have 2 Columns, both sized at 50% and one Row, set to Autosize.
    2. Set the Location.X of the TableLayoutPanel to 0 and adjust its width to the width of the Form.
    3. Set the TLP Anchor property to Left and Right
    4. Adjust-drag the Row height to be ~twice the size of the Button it will host
  • Add one Button to the Form
    1. Adjust the appearance of the Button as required.
    2. CTRL-Drag the Button to create an exact duplicate
    3. Add the two Buttons to the two cells of the TableLayoutPanel
    4. SHIFT-Select both Buttons and set the Dock property to DockStyle.Fill
    5. You can now adjust the Margin property of the Buttons (still both selected, so the same settings will apply to both) to modify the space between the controls
  • Re-adjust the TableLayoutPanel's only Row height as needed.
  • Extra: if you have only these controls on the Form, you may want to fix the MinimumSize of the Form, to avoid that, when the Form is resized, your controls are shrinked beyond recognition, ruining the overall layout: resize the Form in the Designer to a point where the hosted controls layout is compromised, find a suitable minimum size and use this measure as the Form's MinimumSize property. The MinimumSize can be set using only the Width or the Height measure (e.g., (100, 0)). This limits the Form's Width but not the Height. Or the opposite, of course.

If, when dragging the Buttons inside the TableLayoutPanel, the Buttons are not automatically inserted at the Top-Left position of the cell and instead they appear positioned in a random place, then the TableLayoutPanel has gone rogue and needs to be put down. Delete it and drop another on the Form. Rinse and repeat.

This may happen if you tamper with the layout a bit. Better start over than trying to correct the problem.

TableLayoutPanel Control Overview



来源:https://stackoverflow.com/questions/55827720/how-can-i-link-a-components-size-to-the-window-size

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!