- Walkthrough: Lay out controls with padding, margins, and the AutoSize property
- Prerequisites
- Create the project
- Set margins for controls
- Arrange controls on your form using the Margin property
- Set padding for controls
- Arrange controls on your form using padding
- Size controls automatically
- Arrange controls on your form using the AutoSize property
- AutoSize and AutoSizeMode properties
- Use the AutoSizeMode property
- Next steps
- Padding Структура
- Определение
- Примеры
- Комментарии
- Конструкторы
- Свойства
- Методы
- Операторы
Walkthrough: Lay out controls with padding, margins, and the AutoSize property
Precise placement of controls on your form is a high priority for many applications. The Windows Forms Designer in Visual Studio gives you many layout tools to accomplish this. Three of the most important are the Margin, Padding, and AutoSize properties, which are present on all Windows Forms controls.
The Margin property defines the space around the control that keeps other controls a specified distance from the control’s borders.
The Padding property defines the space in the interior of a control that keeps the control’s content (for example, the value of its Text property) a specified distance from the control’s borders.
The following illustration shows the Padding and Margin properties on a control.
The AutoSize property tells a control to automatically size itself to its contents. It will not resize itself to be smaller than the value of its original Size property, and it will account for the value of its Padding property.
Prerequisites
You’ll need Visual Studio to complete this walkthrough.
Create the project
In Visual Studio, create a Windows Application project called LayoutExample .
Select the form in the Windows Forms Designer.
Set margins for controls
You can set the default distance between your controls using the Margin property. When you move a control close enough to another control, you will see a snapline that shows the margins for the two controls. The control you are moving will also snap to the distance defined by the margins.
Arrange controls on your form using the Margin property
Drag two Button controls from the Toolbox onto your form.
Select one of the Button controls and move it close to the other, until they are almost touching.
Observe the snapline that appears between them. This distance is the sum of the two controls’ Margin values. The control you are moving snaps to this distance. For details, see Walkthrough: Arranging Controls on Windows Forms Using Snaplines.
Change the Margin property of one of the controls by expanding the Margin entry in the Properties window and setting the All property to 20.
Select one of the Button controls and move it close to the other.
The snapline defining the sum of the margin values is longer and that the control snaps to a greater distance from the other control.
Change the Margin property of the selected control by expanding the Margin entry in the Properties window and setting the Top property to 5.
Move the selected control below the other control and observe that the snapline is shorter. Move the selected control to the left of the other control and observe that the snapline retains the value observed in step 4.
You can set each of the aspects of the Margin property, Left, Top, Right, Bottom, to different values, or you can set them all to the same value with the All property.
Set padding for controls
To achieve the precise layout required for your application, your controls will often contain child controls. When you want to specify the proximity of the child control’s border to the parent control’s border, use the parent control’s Padding property in conjunction with the child control’s Margin property. The Padding property is also used to control the proximity of a control’s content (for example, a Button control’s Text property) to its borders.
Arrange controls on your form using padding
Drag a Button control from the Toolbox onto your form.
Change the value of the Button control’s AutoSize property to true.
Change the Padding property by expanding the Padding entry in the Properties window and setting the All property to 5.
The control expands to provide room for the new padding.
Drag a GroupBox control from the Toolbox onto your form. Drag a Button control from the Toolbox into the GroupBox control. Position the Button control so it is flush with the lower-right corner of the GroupBox control.
Observe the snaplines that appear as the Button control approaches the bottom and right borders of the GroupBox control. These snaplines correspond to the Margin property of the Button.
Change the GroupBox control’s Padding property by expanding the Padding entry in the Properties window and setting the All property to 20.
Select the Button control within the GroupBox control and move it toward the center of the GroupBox.
The snaplines appear at a greater distance from the borders of the GroupBox control. This distance is the sum of the Button control’s Margin property and the GroupBox control’s Padding property.
Size controls automatically
In some applications, the size of a control will not be the same at run time as it was at design time. The text of a Button control, for example, may be taken from a database, and its length are not known in advance.
When the AutoSize property is set to true , the control will size itself to its content. For more information, see AutoSize Property Overview.
Arrange controls on your form using the AutoSize property
Drag a Button control from the Toolbox onto your form.
Change the value of the Button control’s AutoSize property to true.
Change the Button control’s Text property to This button has a long string for its Text property.
When you commit the change, the Button control resizes itself to fit the new text.
Drag another Button control from the Toolbox onto your form.
Change the Button control’s Text property to «This button has a long string for its Text property.«
When you commit the change, the Button control does not resize itself, and the text is clipped by the right edge of the control.
Change the Padding property by expanding the Padding entry in the Properties window and setting the All property to 5.
The text in the control’s interior is clipped on all four sides.
Change the Button control’s AutoSize property to true.
The Button control resizes itself to encompass the entire string. Also, padding has been added around the text, causing the Button control to expand in all four directions.
Drag a Button control from the Toolbox onto your form. Position it near the lower-right corner of the form.
Change the value of the Button control’s AutoSize property to true.
Set the Button control’s Anchor property to Right, Bottom.
Change the Button control’s Text property to «This button has a long string for its Text property.«
When you commit the change, the Button control resizes itself toward the left. In general, automatic sizing will increase the size of a control in the direction opposite its Anchor property setting.
AutoSize and AutoSizeMode properties
Some controls support the AutoSizeMode property, which gives you more fine-grained control over the automatic sizing behavior of a control.
Use the AutoSizeMode property
Drag a Panel control from the Toolbox onto your form.
Set the value of the Panel control’s AutoSize property to true.
Drag a Button control from the Toolbox into the Panel control.
Place the Button control near the lower-right corner of the Panel control.
Select the Panel control and grab the lower-right sizing handle. Resize the Panel control to be larger and smaller.
You can freely resize the Panel control, but you cannot size it smaller than the position of the Button control’s lower-right corner. This behavior is specified by the default value of the AutoSizeMode property, which is GrowOnly.
Set the value of the Panel control’s AutoSizeMode property to GrowAndShrink.
The Panel control sizes itself to surround the Button control. You cannot resize the Panel control.
Drag the Button control toward the upper-left corner of the Panel control.
The Panel control resizes to the Button control’s new position.
Next steps
There are many other layout features for arranging controls in your Windows Forms applications. Here are some combinations you might try:
Build a form using a TableLayoutPanel control. For details, see Walkthrough: Arranging Controls on Windows Forms Using a TableLayoutPanel. Try changing the values of the TableLayoutPanel control’s Padding property, as well as the Margin property on its child controls.
Experiment with docking child controls in a Panel control. The Padding property is a more general realization of the DockPadding property, and you can satisfy yourself that this is the case by putting a child control in a Panel control and setting the child control’s Dock property to Fill. Set the Panel control’s Padding property to various values and note the effect.
Padding Структура
Определение
Представляет сведения о внутренних полях и полях, связанных с элементом пользовательского интерфейса. Represents padding or margin information associated with a user interface (UI) element.
Примеры
В следующем примере кода показано использование свойства Padding для создания контура вокруг RichTextBox элемента управления. The following code example demonstrates how to use the Padding property to create an outline around a RichTextBox control.
Комментарии
PaddingСтруктура представляет заполнение или маржу, связанную с прямоугольным элементом пользовательского интерфейса, например элементом управления. The Padding structure represents the padding or margin associated with a rectangular UI element such as a control. Заполнение — это внутреннее пространство между телом элемента пользовательского интерфейса и его границей. The padding is the internal space between the body of the UI element and its edge. В отличие от этого, поле — это расстояние, которое отделяет соседние края двух смежных элементов пользовательского интерфейса. In contrast, a margin is the distance separating the adjoining edges of two adjacent UI elements. Из-за структурных сходствов Padding используется для представления как заполнения, так и полей. Because of structural similarities, Padding is used to represent both padding and margins.
Схему, иллюстрирующие Padding Margin Свойства и элемента управления, см. в разделе Margin and Padding in Windows Forms Controls. For a diagram that illustrates the Padding and Margin properties on a control, see Margin and Padding in Windows Forms Controls.
Заполнение влияет на элементы управления, которые являются контейнерами, а не с элементами управления, которые не являются. Padding has a different effect on controls that are containers than on controls that are not. Например, в Panel элементе управления Padding свойство определяет интервал между границей Panel и ее дочерними элементами управления. For example, in a Panel control, the Padding property defines the spacing between the border of the Panel and its child controls. Для Button элемента управления Padding свойство определяет интервал между границей Button элемента управления и его содержащим текстом. For a Button control, the Padding property defines the spacing between the border of the Button control and its contained text.
Помимо стандартных методов и свойств, Padding также определяет следующие члены уровня типа: In addition to typical methods and properties, Padding also defines the following type-level members:
EmptyПоле, представляющее предопределенную без Padding заполнения. The Empty field, which represents a predefined Padding with no padding.
Набор операторов для выполнения общих арифметических операций для класса, таких как добавление двух Padding объектов вместе. A set of operators for performing common arithmetic operations for the class, such as adding two Padding objects together. Для языков, которые не поддерживают перегрузку операторов, эти члены можно вызывать с помощью альтернативного синтаксиса метода. For languages that do not support operator overloading, you can invoke these members by using alternative method syntax.
HorizontalСвойства, Vertical и Size , которые предоставляют объединенные значения, удобные для использования в пользовательских вычислениях макета. The Horizontal, Vertical, and Size properties, which provide combined values that are convenient for use in custom layout calculations.
Конструкторы
Инициализирует новый экземпляр класса Padding, используя предоставленный размер внутренних полей для всех краев. Initializes a new instance of the Padding class using the supplied padding size for all edges.
Инициализирует новый экземпляр класса Padding, используя особый размер внутренних полей для каждого края. Initializes a new instance of the Padding class using a separate padding size for each edge.
Предоставляет объект Padding без внутренних полей. Provides a Padding object with no padding.
Свойства
Получает или задает значение для всех краев. Gets or sets the padding value for all the edges.
Получает или задает значение внутренних полей для нижнего края. Gets or sets the padding value for the bottom edge.
Получает объединенные внутренние поля для правого и левого краев. Gets the combined padding for the right and left edges.
Получает или задает значение внутренних полей для левого края. Gets or sets the padding value for the left edge.
Получает или задает значение внутренних полей для правого края. Gets or sets the padding value for the right edge.
Получает сведения о внутренних полях в форме Size. Gets the padding information in the form of a Size.
Получает или задает значение внутренних полей для верхнего края. Gets or sets the padding value for the top edge.
Получает объединенные внутренние поля для верхнего и нижнего краев. Gets the combined padding for the top and bottom edges.
Методы
Вычисляет сумму двух заданных значений Padding. Computes the sum of the two specified Padding values.
Определяет, эквивалентно ли значение заданного объекта текущему атрибуту Padding. Determines whether the value of the specified object is equivalent to the current Padding.
Создает хэш-код для текущего атрибута Padding. Generates a hash code for the current Padding.
Вычитает одно указанное значение типа Padding из другого. Subtracts one specified Padding value from another.
Возвращает строку, которая представляет текущий объект Padding. Returns a string that represents the current Padding.
Операторы
Выполняет векторное добавление для двух указанных объектов Padding, что приводит к созданию нового объекта Padding. Performs vector addition on the two specified Padding objects, resulting in a new Padding.
Проверяет эквивалентность двух указанных объектов Padding. Tests whether two specified Padding objects are equivalent.
Проверяет неравенство двух указанных объектов Padding. Tests whether two specified Padding objects are not equivalent.
Выполняет векторное вычитание двух указанных объектов Padding, что приводит к созданию нового объекта Padding. Performs vector subtraction on the two specified Padding objects, resulting in a new Padding.