- System. Windows. Forms. Integration Пространство имен
- Классы
- Делегаты
- Комментарии
- Свойства элементов управления Windows Forms Properties in Windows Forms Controls
- в этом разделе In This Section
- Справочник Reference
- Связанные разделы Related Sections
- Form. Dialog Result Property
- Definition
- Property Value
- Exceptions
- Examples
- Remarks
- Form. Size Property
- Definition
- Property Value
- Examples
- Remarks
- Размещение и компоновка элементов управления (Windows Forms .NET) Position and layout of controls (Windows Forms .NET)
- Фиксированное расположение и размер Fixed position and size
- Автоматическое размещение и размер Automatic placement and size
- Панель закрепления Dock
- Привязка Anchor
- Автоматическое изменение размеров Automatic sizing
- Контейнер: Form Container: Form
- Контейнер: Panel Container: Panel
- Контейнер: Группа Container: Group box
- Контейнер: Потоковый макет Container: Flow Layout
- Контейнер: табличный макет Container: Table layout
- Контейнер: контейнер разбиения Container: Split container
- Контейнер: Элемент управления табуляции Container: Tab control
System. Windows. Forms. Integration Пространство имен
Содержит классы, предназначенные для поддержки взаимодействия элементов управления Windows Forms и WPF. Contains classes that support interoperation of Windows Forms and WPF controls.
Классы
Предоставляет данные для событий ChildChanged и ChildChanged . Provides data for the ChildChanged and ChildChanged events.
Элемент управления Windows Forms, который может использоваться для размещения элемента Windows Presentation Foundation (WPF). A Windows Forms control that can be used to host a Windows Presentation Foundation (WPF) element.
Предоставляет базовый класс для классов EventArgs, поддерживающих необязательный выброс исключений. Provides a base class for EventArgs classes which support optionally raising exceptions.
Предоставляет данные для события LayoutError. Provides data for the LayoutError event.
Предоставляет способ преобразования значений свойств между элементами Windows Forms controls и Windows Presentation Foundation (WPF). Provides a way to translate property values between Windows Forms controls and Windows Presentation Foundation (WPF) elements.
Предоставляет данные для события PropertyMappingError. Provides data for the PropertyMappingError event.
Элемент, который позволяет размещать элемент управления Windows Forms на странице WPF. An element that allows you to host a Windows Forms control on a WPF page.
Делегаты
Предоставляет функцию преобразования для сопоставляемого свойства родительского элемента управления. Provides a translation function for a mapped property of the host control.
Комментарии
System.Windows.Forms.IntegrationПространство имен содержит классы, обеспечивающие взаимодействие между Windows Forms и технологиями WPF. The System.Windows.Forms.Integration namespace contains classes that enable interoperation between the Windows Forms and WPF technologies. При использовании System.Windows.Forms.Integration классов можно размещать элементы управления Windows Forms на страницах WPF, а элементы WPF — в приложениях на основе Windows Forms. When you use System.Windows.Forms.Integration classes, you can host Windows Forms controls on WPF pages, and WPF elements in Windows Forms-based applications.
Двумя ключевыми классами, реализующими возможности взаимодействия, являются WindowsFormsHost и ElementHost . The two key classes that implement interoperation capabilities are WindowsFormsHost and ElementHost. Используемый класс зависит от реализации элемента управления: Which class you use depends on your control implementation:
Используйте WindowsFormsHost класс, если необходимо использовать элемент управления Windows Forms на странице WPF. Use the WindowsFormsHost class when you must use a Windows Forms control on a WPF page.
Используйте ElementHost класс, если необходимо использовать элемент WPF в приложении на основе Windows Forms. Use the ElementHost class when you must use a WPF element in a Windows Forms-based application.
Свойства элементов управления Windows Forms Properties in Windows Forms Controls
Элемент управления Windows Forms наследует множество свойств, образующих базовый класс System.Windows.Forms.Control . A Windows Forms control inherits many properties form the base class System.Windows.Forms.Control. К ним относятся такие свойства Font , как,, ForeColor ,, BackColor Bounds ClientRectangle , DisplayRectangle , Enabled , Focused . Height Width Visible AutoSize и многие другие. These include properties such as Font, ForeColor, BackColor, Bounds, ClientRectangle, DisplayRectangle, Enabled, Focused, Height, Width, Visible, AutoSize, and many others. Дополнительные сведения о наследованных свойствах см. в разделе System.Windows.Forms.Control . For details about inherited properties, see System.Windows.Forms.Control.
Вы можете переопределять наследуемые свойства в элементе управления, а также задавать новые свойства. You can override inherited properties in your control as well as define new properties.
в этом разделе In This Section
Определение свойства Defining a Property
Показывает, как реализовать свойство настраиваемого элемента управления или компонента и интегрировать свойство в среду разработки. Shows how to implement a property for a custom control or component and shows how to integrate the property into the design environment.
Определение значений по умолчанию с помощью методов ShouldSerialize и Reset Defining Default Values with the ShouldSerialize and Reset Methods
Показывает, как определить значения свойства по умолчанию для настраиваемого элемента управления или компонента. Shows how to define default property values for a custom control or component.
События изменения свойств Property-Changed Events
Показывает, как включить уведомления об изменении свойств при изменении значения свойства. Describes how to enable property-change notifications when a property value changes.
Практическое руководство. Обеспечение доступа к свойствам составных элементов управления How to: Expose Properties of Constituent Controls
Показывает, как предоставить доступ к свойствам составных элементов управления в настраиваемом составном элементе управления. Shows how to expose properties of constituent controls in a custom composite control.
Реализация методов в специализированных элементах управления Method Implementation in Custom Controls
Показывает, как реализовывать методы в настраиваемых элементах управления и компонентах. Describes how to implement methods in custom controls and components.
Справочник Reference
UserControl
Описание базового класса для реализации составных элементов управления. Documents the base class for implementing composite controls.
TypeConverterAttribute
Документирует атрибут, указывающий, TypeConverter используемый для пользовательского типа свойства. Documents the attribute that specifies the TypeConverter to use for a custom property type.
EditorAttribute
Документирует атрибут, указывающий, UITypeEditor используемый для пользовательского свойства. Documents the attribute that specifies the UITypeEditor to use for a custom property.
Связанные разделы Related Sections
Атрибуты в элементах управления Windows Forms Attributes in Windows Forms Controls
Описываются атрибуты, которые можно применять к свойствам или другим членам пользовательских элементов управления и компонентов. Describes the attributes you can apply to properties or other members of your custom controls and components.
Атрибуты времени разработки для компонентов Design-Time Attributes for Components
Перечислены атрибуты метаданных, которые нужно применить к компонентам и элементам управления, чтобы они корректно отображались в режиме разработки в визуальных конструкторах. Lists metadata attributes to apply to components and controls so that they are displayed correctly at design time in visual designers.
Расширение поддержки времени разработки Extending Design-Time Support
Описывается, как реализовать такие классы, как редакторы и конструкторы, обеспечивающие поддержку во время разработки. Describes how to implement classes such as editors and designers that provide design-time support.
Form. Dialog Result Property
Definition
Gets or sets the dialog result for the form.
Property Value
A DialogResult that represents the result of the form when used as a dialog box.
Exceptions
The value specified is outside the range of valid values.
Examples
The following example displays a form as a dialog box and displays a message box indicating whether the OK or Cancel button of the form was clicked by referencing the DialogResult property of the form.
Remarks
The dialog result of a form is the value that is returned from the form when it is displayed as a modal dialog box. If the form is displayed as a dialog box, setting this property with a value from the DialogResult enumeration sets the value of the dialog box result for the form, hides the modal dialog box, and returns control to the calling form. This property is typically set by the DialogResult property of a Button control on the form. When the user clicks the Button control, the value assigned to the DialogResult property of the Button is assigned to the DialogResult property of the form.
When a form is displayed as a modal dialog box, clicking the Close button (the button with an X in the top-right corner of the form) causes the form to be hidden and the DialogResult property to be set to DialogResult.Cancel . The Close method is not automatically called when the user clicks the Close button of a dialog box or sets the value of the DialogResult property. Instead, the form is hidden and can be shown again without creating a new instance of the dialog box. Because of this behavior, you must call the Dispose method of the form when the form is no longer needed by your application.
You can use this property to determine how a dialog box is closed in order to properly process the actions performed in the dialog box.
You can override the value assigned to the DialogResult property when the user clicks the Close button by setting the DialogResult property in an event handler for the Closing event of the form.
If a Form is displayed as a modeless window, the value returned by the DialogResult property might not return a value assigned to the form because the form’s resources are automatically released when the form is closed.
Form. Size Property
Definition
Gets or sets the size of the form.
Property Value
A Size that represents the size of the form.
Examples
The following example demonstrates how to create a form that is displayed with an opacity level of 75 percent. The example code creates a new form that is positioned in the center of the screen with an Opacity property set to change the opacity level of the form. The example code also sets the Size property to provide a larger sized form than the default size of the form. This example requires that the method defined in this example is called from another form in an event handler or other method.
Remarks
This property allows you to set both the height and width (in pixels) of the form at the same time instead of setting the Height and Width properties individually. If you want to set the size and location of a form, you can use the DesktopBounds property to size and locate the form based on desktop coordinates or use the Bounds property of the Control class to set the size and location of the form based on screen coordinates.
The maximum value of this property is limited by the resolution of the screen on which the form runs. The value cannot be greater than 12 pixels over each screen dimension (horizontal + 12 and vertical + 12).
On Pocket PC devices, you can create a resizable window by setting FormBorderStyle to None and removing any MainMenu control. On SmartPhone devices, you can never resize a Form — it will always fill the entire screen.
Размещение и компоновка элементов управления (Windows Forms .NET) Position and layout of controls (Windows Forms .NET)
Размещение элементов управления в Windows Forms определяется не только элементом управления, но и родительским элементом управления. Control placement in Windows Forms is determined not only by the control, but also by the parent of the control. В этой статье описываются различные параметры элементов управления, а также различные типы родительских контейнеров, которые влияют на компоновку. This article describes the different settings provided by controls and the different types of parent containers that affect layout.
Документация для Руководства по рабочему столу по .NET 5 (и .NET Core) находится в разработке. The Desktop Guide documentation for .NET 5 (and .NET Core) is under construction.
Фиксированное расположение и размер Fixed position and size
Расположение на родительском элементе определяется значением свойства Location относительно левого верхнего угла поверхности родительского элемента управления. The position a control appears on a parent is determined by the value of the Location property relative to the top-left of the parent surface. Координата верхнего левого угла в родительском элементе — (x0,y0) . The top-left position coordinate in the parent is (x0,y0) . Размер элемента управления определяется свойством Size и представляет ширину и высоту элемента управления. The size of the control is determined by the Size property and represents the width and height of the control.
При добавлении элемента управления на родительский элемент, который применяет автоматическое размещение, положение и размер элемента управления изменяются. When a control is added to a parent that enforces automatic placement, the position and size of the control is changed. В этом случае в зависимости от типа родительского элемента скорректировать расположение и размер элемента управления вручную не удастся. In this case, the position and size of the control may not be manually adjusted, depending on the type of parent.
Свойства MaximumSize и MinimumSize помогают задать минимальное и максимальное пространство, которое может использовать элемент управления. The MaximumSize and MinimumSize properties help set the minimum and maximum space a control can use.
Автоматическое размещение и размер Automatic placement and size
Элементы управления могут размещаться в родительском элементе автоматически. Controls can be automatically placed within their parent. Некоторые родительские контейнеры выполняют размещение принудительно, в то время как другие используют параметры управления, определяющие размещение. Some parent containers force placement while others respect control settings that guide placement. Существует два свойства элемента управления, которые помогают автоматически размещать и изменять размер в пределах родительского элемента: Dock и Anchor. There are two properties on a control that help automatic placement and size within a parent: Dock and Anchor.
На автоматическое размещение может влиять порядок отображения. Drawing order can affect automatic placement. Порядок, в котором отображается элемент управления, определяется индексом элемента управления в коллекции Controls родительского элемента. The order in which a control is drawn determined by the control’s index in the parent’s Controls collection. Этот индекс называется Z-order . This index is known as the Z-order. Каждый элемент управления отображается в порядке, в котором он представлен в коллекции. Each control is drawn in the reverse order they appear in the collection. Это означает, что первый элемент в коллекции отображается последним, а последний элемент — первым. Meaning, the collection is a first-in-last-drawn and last-in-first-drawn collection.
Свойства MinimumSize и MaximumSize помогают задать минимальное и максимальное пространство, которое может использовать элемент управления. The MinimumSize and MaximumSize properties help set the minimum and maximum space a control can use.
Панель закрепления Dock
Свойство Dock задает, какая граница элемента управления выравнивается по соответствующей стороне родительского элемента и как изменяется размер элемента управления в пределах родительского элемента. The Dock property sets which border of the control is aligned to the corresponding side of the parent, and how the control is resized within the parent.
Когда элемент управления закреплен, контейнер определяет пространство, которое он должен занимать, а затем соответствующим образом изменяет размер элемента управления и помещает его. When a control is docked, the container determines the space it should occupy and resizes and places the control. Ширина и высота элемента управления по-прежнему соблюдаются с учетом стиля закрепления. The width and height of the control are still respected based on the docking style. Например, если элемент управления закреплен в верхней части, Height элемента управления соблюдается, тогда как Width корректируется автоматически. For example, if the control is docked to the top, the Height of the control is respected but the Width is automatically adjusted. Если элемент управления закреплен слева, Width элемента управления соблюдается, тогда как Height корректируется автоматически. If a control is docked to the left, the Width of the control is respected but the Height is automatically adjusted.
Location элемента управления нельзя задать вручную, поскольку при закреплении элемента управления его положение контролируется автоматически. The Location of the control can’t be manually set as docking a control automatically controls its position.
Индекс Z-order элемента управления влияет на закрепление. The Z-order of the control does affect docking. После размещения закрепленных элементов управления они занимают выделенное для них пространство. As docked controls are laid out, they use what space is available to them. Например, если элемент управления отображается первым и закрепляется в верхней части, он займет всю ширину контейнера. For example, if a control is drawn first and docked to the top, it will take up the entire width of the container. Если следующий элемент управления закреплен слева, ему будет выделено меньше свободного места. If a next control is docked to the left, it has less vertical space available to it.
При изменении индекса Z-order доступное начальное пространство элемента управления, закрепленного слева, будет больше. If the control’s Z-order is reversed, the control that is docked to the left now has more initial space available. Элемент управления использует всю высоту контейнера. The control uses the entire height of the container. Элемент управления, закрепленный вверху, имеет меньше свободного места. The control that is docked to the top has less horizontal space available to it.
По мере расширения и сжатия контейнера элементы управления, закрепленные в контейнере, перемещаются и изменяют свой размер для сохранения заданных параметров. As the container grows and shrinks, the controls docked to the container are repositioned and resized to maintain their applicable positions and sizes.
Если на одной стороне контейнера закреплены несколько элементов управления, они группируются в соответствии с их индексами Z-order . If multiple controls are docked to the same side of the container, they’re stacked according to their Z-order.
Привязка Anchor
Привязка элемента управления позволяет привязать элемент управления к одной или нескольким сторонам родительского контейнера. Anchoring a control allows you to tie the control to one or more sides of the parent container. По мере изменения размера контейнера любой дочерний элемент управления будет сохранять заданное расстояние до привязанной стороны. As the container changes in size, any child control will maintain its distance to the anchored side.
Элемент управления можно привязать к одной или нескольким сторонам без ограничений. A control can be anchored to one or more sides, without restriction. Привязка задается свойством Anchor. The anchor is set with the Anchor property.
Автоматическое изменение размеров Automatic sizing
Свойство AutoSize позволяет элементу управления изменять свой размер, если это необходимо, в соответствии с размером, заданным свойством PreferredSize. The AutoSize property enables a control to change its size, if necessary, to fit the size specified by the PreferredSize property. Изменение размеров конкретных элементов управления регулируется заданием свойства AutoSizeMode . You adjust the sizing behavior for specific controls by setting the AutoSizeMode property.
Свойство AutoSize поддерживают только некоторые элементы управления. Only some controls support the AutoSize property. Кроме того, некоторые элементы управления, поддерживающие свойство AutoSize, также поддерживают свойство AutoSizeMode . In addition, some controls that support the AutoSize property also supports the AutoSizeMode property.
Всегда истинное поведение Always true behavior | Описание Description |
---|---|
Автоматическое изменение размера — это функция, активируемая во время выполнения. Automatic sizing is a run-time feature. | Это означает, что она никогда не увеличивает и не сжимает элемент управления и не оказывает дальнего влияния. This means it never grows or shrinks a control and then has no further effect. |
Если размер элемента управления изменяется, значение его свойства Location всегда остается постоянным. If a control changes size, the value of its Location property always remains constant. | Когда содержимое элемента управления приводит к увеличению элемента управления, он увеличивается в направлении вправо и вниз. When a control’s contents cause it to grow, the control grows toward the right and downward. Элементы управления не увеличиваются до левого края. Controls do not grow to the left. |
Свойства Dock и Anchor учитываются, если AutoSize имеет значение true . The Dock and Anchor properties are honored when AutoSize is true . | Значение свойства Location элемента управления корректируется на правильное значение. The value of the control’s Location property is adjusted to the correct value. Элемент управления Label является исключением из этого правила. The Label control is the exception to this rule. Если для свойства AutoSize закрепленного элемента управления Label задано значение true , то элемент управления Label не будет растягиваться. When you set the value of a docked Label control’s AutoSize property to true , the Label control will not stretch. |
Свойства MaximumSize и MinimumSize элемента управления всегда учитываются независимо от значения свойства AutoSize. A control’s MaximumSize and MinimumSize properties are always honored, regardless of the value of its AutoSize property. | Свойство AutoSize не влияет на свойства MaximumSize и MinimumSize. The MaximumSize and MinimumSize properties are not affected by the AutoSize property. |
Минимальный размер по умолчанию не задан. There is no minimum size set by default. | Это означает, что если для элемента управления задано сжатие до AutoSize и он не имеет содержимого, значение его свойства Size равно (0x,0y) . This means that if a control is set to shrink under AutoSize and it has no contents, the value of its Size property is (0x,0y) . В этом случае элемент управления будет сжиматься до точки, и он не будет виден. In this case, your control will shrink to a point, and it will not be readily visible. |
Если элемент управления не реализует метод GetPreferredSize, метод GetPreferredSize возвращает последнее значение, присвоенное свойству Size. If a control does not implement the GetPreferredSize method, the GetPreferredSize method returns last value assigned to the Size property. | Это означает, что установка для свойства AutoSize значения true не окажет никакого влияния. This means that setting AutoSize to true will have no effect. |
Элемент управления в ячейке TableLayoutPanel всегда сжимается в соответствии с ячейкой, пока не будет достигнут ее MinimumSize. A control in a TableLayoutPanel cell always shrinks to fit in the cell until its MinimumSize is reached. | Этот размер применяется в качестве максимального размера. This size is enforced as a maximum size. Исключением является случай, когда ячейка входит в строку или столбец AutoSize. This is not the case when the cell is part of an AutoSize row or column. |
Контейнер: Form Container: Form
Form является основным объектом Windows Forms. The Form is the main object of Windows Forms. Формы обычно всегда отображаются в приложении Windows Forms. A Windows Forms application will usually have a form displayed at all times. Формы содержат элементы управления и учитывают свойства Location и Size элемента управления для размещения вручную. Forms contain controls and respect the Location and Size properties of the control for manual placement. Формы также учитывают свойство Dock для автоматического размещения. Forms also respond to the Dock property for automatic placement.
Как правило, на краях формы имеются маркеры, позволяющие пользователю изменить ее размер. Most of the time a form will have grips on the edges that allow the user to resize the form. Свойство Anchor элемента управления позволяет увеличивать и уменьшать размер элемента управления при изменении размера формы. The Anchor property of a control will let the control grow and shrink as the form is resized.
Контейнер: Panel Container: Panel
Элемент управления Panel аналогичен форме в том, что он просто группирует элементы управления вместе. The Panel control is similar to a form in that it simply groups controls together. Он поддерживает те же стили автоматического размещения, что и форма. It supports the same manual and automatic placement styles that a form does. Подробнее см. в разделе Контейнер: Form. For more information, see the Container: Form section.
Панель сливается с родительским элементом и обрезает все области элемента управления, находящиеся за границами панели. A panel blends in seamlessly with the parent, and it does cut off any area of a control that falls out of bounds of the panel. Если элемент управления выходит за границы панели, а свойство AutoScroll имеет значение true , появляются полосы прокрутки, с помощью которых пользователь может прокручивать панель. If a control falls outside the bounds of the panel and AutoScroll is set to true , scroll bars appear and the user can scroll the panel.
В отличие от группы панель не содержит заголовок и границу. Unlike the group box control, a panel doesn’t have a caption and border.
На изображении выше показана панель с заданным свойством BorderStyle, чтобы продемонстрировать границы панели. The image above has a panel with the BorderStyle property set to demonstrate the bounds of the panel.
Контейнер: Группа Container: Group box
Элемент управления GroupBox предоставляет возможность идентифицируемой группировки других элементов управления. The GroupBox control provides an identifiable grouping for other controls. Как правило, группа используется для разделения формы на функциональные области. Typically, you use a group box to subdivide a form by function. Например, у вас может быть форма для ввода персональных данных, в которой следует сгруппировать поля, связанные с адресом. For example, you may have a form representing personal information and the fields related to an address would be grouped together. Во время разработки можно с легкостью переместить группу вместе со всеми содержащимися в ней элементами управления. At design time, it’s easy to move the group box around along with its contained controls.
Группа поддерживает те же стили автоматического размещения, что и форма. The group box supports the same manual and automatic placement styles that a form does. Подробнее см. в разделе Контейнер: Form. For more information, see the Container: Form section. Группа также обрезает любую часть элемента управления, которая выходит за пределы панели. A group box also cuts off any portion of a control that falls out of bounds of the panel.
В отличие от панели, в группе нет возможности прокрутить содержимого и нет полос прокрутки. Unlike the panel control, a group box doesn’t have the capability to scroll content and display scroll bars.
Контейнер: Потоковый макет Container: Flow Layout
Элемент управления FlowLayoutPanel упорядочивает свое содержимое в горизонтальном или вертикальном направлении. The FlowLayoutPanel control arranges its contents in a horizontal or vertical flow direction. Его содержимое может переноситься из одной строки или столбца в следующую строку или столбец. You can wrap the control’s contents from one row to the next, or from one column to the next. Кроме того, вместо переноса содержимое может обрезаться. Alternately, you can clip instead of wrap its contents.
Чтобы определить направление содержимого, задайте свойство FlowDirection. You can specify the flow direction by setting the value of the FlowDirection property. Содержимое элемента управления FlowLayoutPanel размещается правильно при использовании направления справа налево. The FlowLayoutPanel control correctly reverses its flow direction in Right-to-Left (RTL) layouts. С помощью свойства WrapContents можно указать, должно ли содержимое элемента управления FlowLayoutPanel переноситься или обрезаться. You can also specify whether the FlowLayoutPanel control’s contents are wrapped or clipped by setting the value of the WrapContents property.
Если свойству AutoSize присвоено значение true , размер элемента управления FlowLayoutPanel автоматически изменяется в соответствии с содержимым. The FlowLayoutPanel control automatically sizes to its contents when you set the AutoSize property to true . Дочерние элементы управления также получают свойство FlowBreak . It also provides a FlowBreak property to its child controls. Если свойству FlowBreak присвоено значение true , элементы управления внутри элемента FlowLayoutPanel перестают размещаться в текущем направлении и переносятся на следующую строку или в следующий столбец. Setting the value of the FlowBreak property to true causes the FlowLayoutPanel control to stop laying out controls in the current flow direction and wrap to the next row or column.
На изображении выше представлены два элемента управления FlowLayoutPanel с заданным свойством BorderStyle, чтобы продемонстрировать границы панели. The image above has two FlowLayoutPanel controls with the BorderStyle property set to demonstrate the bounds of the control.
Контейнер: табличный макет Container: Table layout
Элемент управления TableLayoutPanel упорядочивает содержимое в сетке. The TableLayoutPanel control arranges its contents in a grid. Так как макет строится как во время разработки, так и во время выполнения, его можно изменять динамически по мере изменения среды приложения. Because the layout is done both at design time and run time, it can change dynamically as the application environment changes. Это позволяет пропорционально изменять размер элементов управления на панели с учетом изменений, например изменения размера родительского элемента управления или изменения длины текста в результате локализации. This gives the controls in the panel the ability to resize proportionally, so they can respond to changes such as the parent control resizing or text length changing because of localization.
Любой элемент управления Windows Forms, включая другие экземпляры TableLayoutPanel, может быть дочерним относительно элемента TableLayoutPanel. Any Windows Forms control can be a child of the TableLayoutPanel control, including other instances of TableLayoutPanel. Это позволяет создавать сложные макеты, динамически меняющиеся во время выполнения. This allows you to construct sophisticated layouts that adapt to changes at run time.
Также можно управлять направлением расширения элемента управления TableLayoutPanel (горизонтальное или вертикальное) после его заполнения дочерними элементами управления. You can also control the direction of expansion (horizontal or vertical) after the TableLayoutPanel control is full of child controls. По умолчанию элемент управления TableLayoutPanel развертывается вниз путем добавления строк. By default, the TableLayoutPanel control expands downward by adding rows.
Для изменения размера и стиля строк и столбцов можно использовать свойства RowStyles и ColumnStyles. You can control the size and style of the rows and columns by using the RowStyles and ColumnStyles properties. Свойства строк и столбцов можно задавать по отдельности. You can set the properties of rows or columns individually.
Элемент управления TableLayoutPanel добавляет следующие свойства в свои дочерние элементы управления: Cell , Column , Row , ColumnSpan и RowSpan . The TableLayoutPanel control adds the following properties to its child controls: Cell , Column , Row , ColumnSpan , and RowSpan .
На изображении выше показана таблица с заданным свойством CellBorderStyle, чтобы продемонстрировать границы каждой ячейки. The image above has a table with the CellBorderStyle property set to demonstrate the bounds of each cell.
Контейнер: контейнер разбиения Container: Split container
Элемент управления Windows Forms SplitContainer состоит из двух панелей, разделенных подвижной полосой. The Windows Forms SplitContainer control can be thought of as a composite control; it’s two panels separated by a movable bar. При наведении указателя мыши на полосу его форма изменяется, показывая, что полоса является перемещаемой. When the mouse pointer is over the bar, the pointer changes shape to show that the bar is movable.
С помощью элемента управления SplitContainer можно создавать сложные пользовательские интерфейсы. Часто выбор на одной панели определяет объекты, представленные на другой. With the SplitContainer control, you can create complex user interfaces; often, a selection in one panel determines what objects are shown in the other panel. Такой подход является эффективным для отображения и просмотра информации. This arrangement is effective for displaying and browsing information. Две панели позволяют группировать информацию, а полоса или разделитель упрощают изменение размера панелей. Having two panels lets you aggregate information in areas, and the bar, or «splitter,» makes it easy for users to resize the panels.
На изображении выше имеется контейнер разбиения для создания левой и правой областей. The image above has a split container to create a left and right pane. В правой панели содержится второй контейнер разбиения, для которого свойству Orientation задано значение Vertical. The right pane contains a second split container with the Orientation set to Vertical. Свойство BorderStyle задается, чтобы продемонстрировать границы каждой панели. The BorderStyle property is set to demonstrate the bounds of each panel.
Контейнер: Элемент управления табуляции Container: Tab control
Элемент управления TabControl используется для отображения нескольких вкладок, аналогичных разделителям в записной книжке или меткам в наборе папок в картотеке. The TabControl displays multiple tabs, like dividers in a notebook or labels in a set of folders in a filing cabinet. Вкладки могут содержать изображения и другие элементы управления. The tabs can contain pictures and other controls. Используйте вкладки для создания многостраничного диалогового окна, которое появляется во многих местах в операционной системе Windows, например на панели управления и в свойствах отображения. Use the tab control to produce the kind of multiple-page dialog box that appears many places in the Windows operating system, such as the Control Panel and Display Properties. Кроме того, TabControl можно использовать для создания страниц свойств, которые используются для задания группы связанных свойств. Additionally, the TabControl can be used to create property pages, which are used to set a group of related properties.
Наиболее важным свойством TabControl является TabPages, которое содержит отдельные вкладки. The most important property of the TabControl is TabPages, which contains the individual tabs. Каждая отдельная вкладка является объектом TabPage. Each individual tab is a TabPage object.