Windows forms dock form

Control. Dock Property

Definition

Gets or sets which control borders are docked to its parent control and determines how a control is resized with its parent.

Property Value

One of the DockStyle values. The default is None.

Exceptions

The value assigned is not one of the DockStyle values.

Examples

The following code example creates a GroupBox and sets some of its common properties. The example creates a TextBox and sets its Location within the group box. Next, it sets the Text property of the group box, and docks the group box to the top of the form. Lastly, it disables the group box by setting the Enabled property to false , which causes all controls contained within the group box to be disabled.

Remarks

Use the Dock property to define how a control is automatically resized as its parent control is resized. For example, setting Dock to DockStyle.Left causes the control to align itself with the left edges of its parent control and to resize as the parent control is resized. Controls are docked in their Z-order, which is the visual layering of controls on a form along the form’s Z-axis (depth).

A control can be docked to one edge of its parent container or can be docked to all edges and fill the parent container.

Setting the Margin property on a docked control has no effect on the distance of the control from the edges of its container.

The Anchor and Dock properties are mutually exclusive. Only one can be set at a time, and the last one set takes precedence.

Notes to Inheritors

When overriding the Dock property in a derived class, use the base class’s Dock property to extend the base implementation. Otherwise, you must provide all the implementation. You are not required to override both the get and set methods of the Dock property; you can override only one if needed.

Control. Dock Свойство

Определение

Возвращает или задает границы элемента управления, прикрепленные к его родительскому элементу управления, и определяет способ изменения размеров элемента управления с его родительским элементом управления. Gets or sets which control borders are docked to its parent control and determines how a control is resized with its parent.

Значение свойства

Одно из значений перечисления DockStyle. One of the DockStyle values. Значение по умолчанию — None. The default is None.

Исключения

Назначенное значение не является одном из значений DockStyle. The value assigned is not one of the DockStyle values.

Примеры

В следующем примере кода создается GroupBox и задаются некоторые общие свойства. The following code example creates a GroupBox and sets some of its common properties. В примере создается TextBox и задается Location в поле группы. The example creates a TextBox and sets its Location within the group box. Затем задается Text свойство поля группы и закрепляет поле группы в верхней части формы. Next, it sets the Text property of the group box, and docks the group box to the top of the form. Наконец, он отключает поле группы, присвоив Enabled свойству значение false , которое приводит к отключению всех элементов управления, содержащихся в поле группы. Lastly, it disables the group box by setting the Enabled property to false , which causes all controls contained within the group box to be disabled.

Комментарии

Используйте Dock свойство, чтобы определить, как автоматически изменяется размер элемента управления при изменении размера его родительского элемента управления. Use the Dock property to define how a control is automatically resized as its parent control is resized. Например, если задать Dock для параметра значение, DockStyle.Left то элемент управления будет выключаться по левому краю родительского элемента управления и изменять его размер при изменении размера родительского элемента управления. For example, setting Dock to DockStyle.Left causes the control to align itself with the left edges of its parent control and to resize as the parent control is resized. Элементы управления закрепляются в Z-порядке, который является визуальным слоем элементов управления на форме вдоль оси Z формы (глубина). Controls are docked in their Z-order, which is the visual layering of controls on a form along the form’s Z-axis (depth).

Элемент управления можно закрепить на одной границе родительского контейнера или прикрепить ко всем краям и заполнить родительский контейнер. A control can be docked to one edge of its parent container or can be docked to all edges and fill the parent container.

Установка Margin свойства для закрепленного элемента управления не влияет на расстояние элемента управления от границ контейнера. Setting the Margin property on a docked control has no effect on the distance of the control from the edges of its container.

AnchorСвойства и Dock являются взаимоисключающими. The Anchor and Dock properties are mutually exclusive. В каждый момент времени может быть задан только один, а последний набор имеет приоритет. Only one can be set at a time, and the last one set takes precedence.

Примечания для тех, кто наследует этот метод

При переопределении Dock свойства в производном классе используйте свойство базового класса Dock для расширения базовой реализации. When overriding the Dock property in a derived class, use the base class’s Dock property to extend the base implementation. В противном случае необходимо предоставить всю реализацию. Otherwise, you must provide all the implementation. Переопределение методов и для свойства не требуется get set ; при Dock необходимости можно переопределить только одно из них. You are not required to override both the get and set methods of the Dock property; you can override only one if needed.

Dock Style Перечисление

Определение

Задает позицию и способ закрепления элемента управления. Specifies the position and manner in which a control is docked.

Нижний край элемента управления закрепляется в нижней части содержащего его элемента управления. The control’s bottom edge is docked to the bottom of its containing control.

Все края элемента управления закрепляются у краев содержащего его элемента управления, а их размеры изменяются соответствующим образом. All the control’s edges are docked to the all edges of its containing control and sized appropriately.

Левый край элемента управления закрепляется в левой части содержащего его элемента управления. The control’s left edge is docked to the left edge of its containing control.

Элемент управления не закреплен. The control is not docked.

Правый край элемента управления закрепляется в правой части содержащего его элемента управления. The control’s right edge is docked to the right edge of its containing control.

Верхний край элемента управления закрепляется в верхней части содержащего его элемента управления. The control’s top edge is docked to the top of its containing control.

Примеры

В следующем примере создается GroupBox и задаются некоторые общие свойства. The following example creates a GroupBox and sets some of its common properties. В примере создается TextBox и задается Location в поле группы. The example creates a TextBox and sets its Location within the group box. Затем задается Text свойство поля группы и закрепляет поле группы в верхней части формы. Next, it sets the Text property of the group box, and docks the group box to the top of the form. Наконец, он отключает поле группы, присвоив Enabled свойству значение false , которое приводит к отключению всех элементов управления, содержащихся в поле группы. Lastly, it disables the group box by setting the Enabled property to false , which causes all controls contained within the group box to be disabled.

Комментарии

Когда элемент управления закрепляется на границе своего контейнера, он всегда позиционируется на эту сторону при изменении размера контейнера. When a control is docked to an edge of its container, it is always positioned flush against that edge when the container is resized. Если к границе прикрепляется несколько элементов управления, то элементы управления отображаются рядом в соответствии с их z-порядком; элементы управления, расположенные выше в z-порядке, располагаются дальше от границы контейнера. If more than one control is docked to an edge, the controls appear side by side according to their z-order; controls higher in the z-order are positioned farther from the container’s edge.

Читайте также:  Jenkins initial admin password windows

Если выбрано левое, правое, верхнее или нижнее, то размеры указанного и противоположного края элемента управления изменяются в соответствии с размерами соответствующих границ элемента управления. If Left, Right, Top, or Bottom is selected, the specified and opposite edges of the control are resized to the size of the containing control’s corresponding edges. Если выбран параметр Fill, размеры всех четырех сторон элемента управления изменяются в соответствии с краями содержащего его элемента управления. If Fill is selected, all four sides of the control are resized to match the containing control’s edges.

Учебник. Начало работы с конструктором Windows Forms Tutorial: Get started with Windows Forms Designer

Конструктор Windows Forms предоставляет множество средств для создания приложений Windows Forms. The Windows Forms Designer provides many tools for building Windows Forms applications. В этой статье показано, как создать приложение с помощью различных средств, предоставляемых конструктором, и выполнять такие задачи: This article illustrates how to build an app using the various tools provided by the designer, including the following tasks:

  • размещать элементы управления с помощью линий привязки; Arrange controls using snaplines.
  • выполнять задачи конструктора с помощью смарт-тегов; Accomplish designer tasks using smart tags.
  • устанавливать поля и отбивки для элементов управления; Set margins and padding for controls.
  • располагать элементы управления с помощью элемента управления TableLayoutPanel; Arrange controls using a TableLayoutPanel control.
  • разделять макет элемента управления с помощью элемента управления SplitContainer; Partition your control’s layout by using a SplitContainer control.
  • просматривать макет в окне «Структура документа»; Navigate your layout with the Document Outline window.
  • размещать элементы управления с отображением размера и сведений о расположении; Position controls with the size and location information display.
  • задавать значения свойств в окне «Свойства». Set property values using the Properties window.

В итоге вы создадите пользовательский элемент управления, используя разнообразные функции макета, которые доступны в конструкторе Windows Forms. When you’re finished, you’ll have a custom control that’s been assembled using many of the layout features available in the Windows Forms Designer. Этот элемент управления реализует пользовательский интерфейс для простого калькулятора. This control implements the user interface (UI) for a simple calculator. На следующем изображении показан общий макет элемента управления калькулятора. The following image shows the general layout of the calculator control:

Создание проекта пользовательского элемента управления Create the custom control project

Первым шагом является создание проекта элемента управления DemoCalculator. The first step is to create the DemoCalculator control project.

Откройте Visual Studio и создайте проект категории Библиотека элементов управления Windows Forms. Open Visual Studio and create a new Windows Forms Control Library project. Задайте проекту имя DemoCalculatorLib. Name the project DemoCalculatorLib.

Чтобы переименовать файл, в обозревателе решений щелкните правой кнопкой мыши элемент UserControl1.vb или UserControl1.cs, выберите Переименовать и замените имя файла на DemoCalculator.vb или DemoCalculator.cs. To rename the file, in Solution Explorer, right-click UserControl1.vb or UserControl1.cs, select Rename, and change the file name to DemoCalculator.vb or DemoCalculator.cs. Чтобы переименовать все ссылки на элемент кода UserControl1, в соответствующем запросе выберите Да. Select Yes when you are asked if you want to rename all references to the code element «UserControl1».

В конструктор Windows Forms отображается поверхность конструктора для элемента управления DemoCalculator. The Windows Forms Designer shows the designer surface for the DemoCalculator control. В этом представлении можно графически спроектировать внешний вид элемента управления, выбрав элементы управления и компоненты на панели элементов и поместив их на поверхности конструктора. In this view, you can graphically design the appearance of the control by selecting controls and components from Toolbox and placing them on the designer surface. Дополнительные сведения см. в статье о разновидностях пользовательских элементов управления. For more information about custom controls, see Varieties of custom controls.

Разработка макета элемента управления Design the control layout

Элемент управления DemoCalculator содержит несколько элементов управления Windows Forms. The DemoCalculator control contains several Windows Forms controls. На этом этапе вы зададите расположение элементов управления с помощью конструктора Windows Forms. In this procedure, you’ll arrange the controls using the Windows Forms Designer.

В конструкторе Windows Forms увеличьте размер элемента управления DemoCalculator, выбрав маркер изменения размера в правом нижнем углу и перетащив его вниз и вправо. In the Windows Forms Designer, change the DemoCalculator control to a larger size by selecting the sizing handle in the lower-right corner and dragging it down and to the right. В правом нижнем углу Visual Studio просмотрите сведения о размере и расположении элементов управления. In the lower-right corner of Visual Studio, find the size and location information for controls. Задайте элементу управления ширину 500 и высоту 400, наблюдая за сведениями о размере при изменении размера элемента управления. Set the size of the control to width 500 and height 400 by watching the size information as you resize the control.

На панели элементов выберите узел Контейнеры, чтобы открыть его. In Toolbox, select the Containers node to open it. Выберите элемент управления SplitContainer и перетащите его на поверхность конструктора. Select the SplitContainer control and drag it onto the designer surface.

Элемент SplitContainer появится на поверхности конструктора элемента управления DemoCalculator. The SplitContainer is placed on the DemoCalculator control’s designer surface.

Размер элемента управления SplitContainer автоматически устанавливается в соответствии с размером элемента управления DemoCalculator. The SplitContainer control sizes itself to the fit the size of the DemoCalculator control. В окне Свойства проверьте свойства, заданные для элемента управления SplitContainer . Look at the Properties window to see the property settings for the SplitContainer control. Найдите свойство Dock. Find the Dock property. Ему задано значение DockStyle.Fill. Это означает, что размер элемента управления SplitContainer устанавливается в соответствии с границами элемента управления DemoCalculator. Its value is DockStyle.Fill, which means the SplitContainer control will always size itself to the boundaries of the DemoCalculator control. Измените размер элемента управления DemoCalculator, чтобы проверить это поведение. Resize the DemoCalculator control to verify this behavior.

В окне Свойства замените значение свойства Dock на None . In the Properties window, change the value of the Dock property to None .

Элемент управления SplitContainer уменьшится до размера по умолчанию и больше не будет меняться при изменении размера элемента управления DemoCalculator. The SplitContainer control shrinks to its default size and no longer follows the size of the DemoCalculator control.

Щелкните глиф смарт-тега () в правом верхнем углу элемента управления SplitContainer . Select the smart tag glyph () on the upper-right corner of the SplitContainer control. Выберите Закрепить в родительском контейнере, чтобы присвоить свойству Dock значение Fill . Select Dock in Parent Container to set the Dock property to Fill .

Элемент управления SplitContainer закрепится по границам элемента управления DemoCalculator. The SplitContainer control docks to the DemoCalculator control’s boundaries.

Для некоторых элементов управления доступны смарт-теги, упрощающие проектирование. Several controls offer smart tags to facilitate design. Дополнительные сведения см. в разделе Пошаговое руководство: выполнение типичных задач с помощью смарт-тегов в элементах управления Windows Forms. For more information, see Walkthrough: Perform common tasks using Smart Tags on Windows Forms controls.

Выберите вертикальную границу между панелями и перетащите ее вправо, так чтобы большую часть заняла левая панель. Select the vertical border between the panels and drag it to the right, so that most of the space is taken by the left panel.

SplitContainer разделяет элемент управления DemoCalculator на две панели с разделяющей их границей, которую можно перемещать. The SplitContainer divides the DemoCalculator control into two panels with a movable border separating them. На левой панели будут находиться кнопки калькулятора и экран, а на правой будет отображаться запись арифметических операций, выполненных пользователем. The panel on the left will hold the calculator buttons and display, and the panel on the right will show a record of the arithmetic operations performed by the user.

В окне Свойства замените значение свойства BorderStyle на Fixed3D . In the Properties window, change the value of the BorderStyle property to Fixed3D .

На панели элементов выберите узел Стандартные элементы управления, чтобы открыть его. In Toolbox, select the Common Controls node to open it. Выберите элемент управления ListView и перетащите его на правую панель элемента управления SplitContainer . Select the ListView control and drag it into the right panel of the SplitContainer control.

Выберите глиф смарт-тега элемента управления ListView . Select the ListView control’s smart tag glyph. На панели смарт-тегов замените значение параметра View на Details . In the smart tag panel, change the View setting to Details .

На панели смарт-тегов выберите Изменить столбцы. In the smart tag panel, select Edit Columns.

Откроется диалоговое окно Редактор коллекции ColumnHeader. The ColumnHeader Collection Editor dialog box opens.

В диалоговом окне Редактор коллекции ColumnHeader выберите Добавить, чтобы добавить столбец в элемент управления ListView . In the ColumnHeader Collection Editor dialog box, select Add to add a column to the ListView control. Измените значение свойства элемента управления Text на Журнал. Change the value of the column’s Text property to History. Нажмите кнопку ОК, чтобы создать столбец. Select OK to create the column.

Читайте также:  Совместим ли мой компьютер с windows 10

На панели смарт-тегов выберите Закрепить в родительском контейнере, а затем щелкните глиф смарт-тега, чтобы закрыть панель смарт-тегов. In the smart tag panel, select Dock in Parent Container, and then select the smart tag glyph to close the smart tag panel.

С панели элементов узла Контейнеры перетащите элемент управления TableLayoutPanel на левую панель элемента управления SplitContainer . From the Containers node Toolbox, drag a TableLayoutPanel control into the left panel of the SplitContainer control.

Элемент управления TableLayoutPanel отобразится на поверхности конструктора с открытой панелью смарт-тегов. The TableLayoutPanel control appears on the designer surface with its smart tag panel open. Элемент управления TableLayoutPanel упорядочивает свои дочерние элементы управления в сетке. The TableLayoutPanel control arranges its child controls in a grid. Элемент управления TableLayoutPanel будет содержать экран и кнопки элемента управления DemoCalculator. The TableLayoutPanel control will hold the DemoCalculator control’s display and buttons. Дополнительные сведения см. в разделе Пошаговое руководство: упорядочение элементов управления в формах Windows Forms с помощью элемента TableLayoutPanel. For more information, see Walkthrough: Arrange controls using a TableLayoutPanel.

На панели смарт-тегов выберите Правка строк и столбцов. Select Edit Rows and Columns on the smart tag panel.

Откроется диалоговое окно Стили столбцов и строк. The Column and Row Styles dialog box opens.

Нажимайте кнопку Добавить, пока не добавятся пять столбцов. Select the Add button until five columns are displayed. Выберите все пять столбцов, а затем в поле Тип размера выберите Процент. Select all five columns, and then select Percent in the Size Type box. Параметру Процент задайте значение 20. Set the Percent value to 20. При этом каждому столбцу задается одинаковая ширина. This sets each column to the same width.

В разделе Показать выберите Строки. Under Show, select Rows.

Нажимайте кнопку Добавить, пока не добавятся пять строк. Select Add until five rows are displayed. Выберите все пять строк, а затем в поле Тип размера выберите Процент. Select all five rows, and the select Percent in the Size Type box. Параметру Процент задайте значение 20. Set the Percent value to 20. При этом каждой строке задается одинаковая высота. This sets each row to the same height.

Нажмите кнопку ОК, чтобы применить изменения, и щелкните глиф смарт-тега, чтобы закрыть панель смарт-тегов. Select OK to accept your changes, and then select the smart tag glyph to close the smart tag panel.

В окне Свойства замените значение свойства Dock на Fill . In the Properties window, change the value of the Dock property to Fill .

Заполнение элемента управления Populate the control

Теперь, когда макет элемента управления настроен, можно добавить в элемент управления DemoCalculator кнопки и экран. Now that the layout of the control is set up, you can populate the DemoCalculator control with buttons and a display.

На панели элементов выберите значок элемента управления TextBox . In Toolbox, select the TextBox control icon.

Элемент управления TextBox помещается в первую ячейку элемента управления TableLayoutPanel . A TextBox control is placed in the first cell of the TableLayoutPanel control.

В окне Свойства замените значение свойства ColumnSpan элемента управления TextBox на 5. In the Properties window, change the value of the TextBox control’s ColumnSpan property to 5.

Элемент управления TextBox переместится в центр своей строки. The TextBox control moves to a position that is centered in its row.

Замените значение свойства Anchor элемента управления TextBox на Left , Right . Change the value of the TextBox control’s Anchor property to Left , Right .

Элемент управления TextBox расширится по горизонтали, заняв все пять столбцов. The TextBox control expands horizontally to span all five columns.

Измените значение свойства TextBox элемента управления TextAlign на Right . Change the value of the TextBox control’s TextAlign property to Right .

В окне Свойства разверните узел свойства Font . In the Properties window, expand the Font property node. Задайте значение 14 для Size и true для Bold у элемента управления TextBox . Set Size to 14, and set Bold to true for the TextBox control.

Выберите элемент управления TableLayoutPanel . Select the TableLayoutPanel control.

На панели элементов выберите значок Button . In Toolbox, select the Button icon.

Элемент управления Button разместится в следующей свободной ячейке элемента управления TableLayoutPanel . A Button control is placed in the next open cell of the TableLayoutPanel control.

На панели элементов выберите Button еще четыре раза, чтобы заполнить вторую строку элемента управления TableLayoutPanel . In Toolbox, select the Button icon four more times to populate the second row of the TableLayoutPanel control.

Выберите все пять элементов управления Button , удерживая нажатой клавишу SHIFT. Select all five Button controls by selecting them while holding down the Shift key. Нажмите клавиши CTRL+C, чтобы скопировать элементы управления Button в буфер обмена. Press Ctrl+C to copy the Button controls to the clipboard.

Трижды нажмите сочетание клавиш CTRL+V, чтобы вставить скопированные элементы управления Button в оставшиеся строки элемента управления TableLayoutPanel . Press Ctrl+V three times to paste copies of the Button controls into the remaining rows of the TableLayoutPanel control.

Выберите все 20 элементов управления Button , удерживая нажатой клавишу SHIFT. Select all 20 Button controls by selecting them while holding down the Shift key.

В окне Свойства замените значение свойства Dock на Fill . In the Properties window, change the value of the Dock property to Fill .

Все элементы управления Button закрепятся в своих ячейках. All the Button controls dock to fill their containing cells.

В окне Свойства разверните узел свойства Margin . In the Properties window, expand the Margin property node. Для All задайте значение 5. Set the value of All to 5.

Всем элементам управления Button задается меньший размер, чтобы увеличить поля между ними. All the Button controls are sized smaller to create a larger margin between them.

Выберите button10 и button20, после чего нажмите клавишу DELETE, чтобы удалить их из макета. Select button10 and button20, and then press Delete to remove them from the layout.

Выберите button5 и button15, после чего замените значение их свойства RowSpan на 2. Select button5 and button15, and then change the value of their RowSpan property to 2. Это будут кнопки очистки и = для элемента управления DemoCalculator. These will be the Clear and = buttons for the DemoCalculator control.

Использование окна структуры документа Use the Document Outline window

Если в элементе управления или форме присутствует несколько элементов управления, перемещаться по макету удобнее с помощью окна «Структура документа». When your control or form is populated with several controls, you may find it easier to navigate your layout with the Document Outline window.

В строке меню выберите Вид > Другие окна > Структура документа. On the menu bar, choose View > Other Windows > Document Outline.

В этом окне структура элемента управления DemoCalculator и его составных элементов управления представлена в виде дерева. The Document Outline window shows a tree view of the DemoCalculator control and its constituent controls. Дочерние элементы управления контейнерных элементов управления, таких как SplitContainer , отображаются в виде подузлов дерева. Container controls like the SplitContainer show their child controls as subnodes in the tree. Окно также позволяет переименовывать размещенные элементы управления. You can also rename controls in place using the Document Outline window.

В окне Структура документа щелкните правой кнопкой мыши элемент button1, чтобы выбрать его, после чего щелкните Переименовать. In the Document Outline window, right-click button1, and then select Rename. Замените его имя на sevenButton. Change its name to sevenButton.

В окне Структура документа замените имена элементов управления Button , заданные конструктором, на имена для рабочей среды согласно следующему списку: Using the Document Outline window, rename the Button controls from the designer-generated name to the production name according to the following list:

button1 на sevenButton; button1 to sevenButton

button2 на eightButton; button2 to eightButton

button3 на nineButton; button3 to nineButton

button4 на divisionButton; button4 to divisionButton

button5 на clearButton; button5 to clearButton

button6 на fourButton; button6 to fourButton

button7 на fiveButton; button7 to fiveButton

button8 на sixButton; button8 to sixButton

button9 на multiplicationButton; button9 to multiplicationButton

button11 на oneButton; button11 to oneButton

button12 на twoButton; button12 to twoButton

button13 на threeButton; button13 to threeButton

button14 на subtractionButton; button14 to subtractionButton

button15 на equalsButton; button15 to equalsButton

button16 на zeroButton; button16 to zeroButton

button17 на changeSignButton; button17 to changeSignButton

button18 на decimalButton; button18 to decimalButton

button19 на additionButton; button19 to additionButton

С помощью окон Структура документа и Свойства измените значения свойства Text для каждого имени элемента управления Button согласно следующему списку: Using the Document Outline and Properties windows, change the Text property value for each Button control name according to the following list:

для элемента управления sevenButton замените свойство текста на 7; Change the sevenButton control text property to 7

для элемента управления eightButton замените свойство текста на 8; Change the eightButton control text property to 8

Читайте также:  Linux для usb дисков

для элемента управления nineButton замените свойство текста на 9; Change the nineButton control text property to 9

для элемента управления divisionButton замените свойство текста на / (косая черта); Change the divisionButton control text property to / (forward slash)

для элемента управления clearButton замените свойство текста на Clear; Change the clearButton control text property to Clear

для элемента управления fourButton замените свойство текста на 4; Change the fourButton control text property to 4

для элемента управления fiveButton замените свойство текста на 5; Change the fiveButton control text property to 5

для элемента управления sixButton замените свойство текста на 6; Change the sixButton control text property to 6

для элемента управления multiplicationButton замените свойство текста на * (звездочка); Change the multiplicationButton control text property to * (asterisk)

для элемента управления oneButton замените свойство текста на 1; Change the oneButton control text property to 1

для элемента управления twoButton замените свойство текста на 2; Change the twoButton control text property to 2

для элемента управления threeButton замените свойство текста на 3; Change the threeButton control text property to 3

для элемента управления subtractionButton замените свойство текста на (дефис); Change the subtractionButton control text property to (hyphen)

для элемента управления equalsButton замените свойство текста на = (знак равенства); Change the equalsButton control text property to = (equals sign)

для элемента управления zeroButton замените свойство текста на 0; Change the zeroButton control text property to 0

для элемента управления changeSignButton замените свойство текста на +/- ; Change the changeSignButton control text property to +/-

для элемента управления decimalButton замените свойство текста на . Change the decimalButton control text property to . (точка); (period)

для элемента управления additionButton замените свойство текста на + (знак «плюс»); Change the additionButton control text property to + (plus sign)

На поверхности конструктора выберите все элементы управления Button , удерживая нажатой клавишу SHIFT. On the designer surface, select all the Button controls by selecting them while holding down the Shift key.

В окне Свойства разверните узел свойства Font . In the Properties window, expand the Font property node. Задайте значение 14 для Size и true для Bold у всех элементов управления Button . Set Size to 14, and set Bold to true for all the Button controls.

На этом разработка элемента управления DemoCalculator завершена. This completes the design of the DemoCalculator control. Остается только добавить логику калькулятора. All that remains is to provide the calculator logic.

Добавление обработчиков событий Implement event handlers

Кнопки в элементе управления DemoCalculator имеют обработчики событий, которые можно использовать для реализации большей части логики калькулятора. The buttons on the DemoCalculator control have event handlers that can be used to implement much of the calculator logic. Конструктор Windows Forms позволяет реализовать заглушки всех обработчиков событий для всех кнопок одним выбором. The Windows Forms Designer enables you to implement the stubs of all the event handlers for all the buttons with one selection.

На поверхности конструктора выберите все элементы управления Button , удерживая нажатой клавишу SHIFT. On the designer surface, select all the Button controls by selecting them while holding down the Shift key.

Выберите один из элементов управления Button . Select one of the Button controls.

В редакторе кода откроются обработчики событий, созданные конструктором. The Code Editor opens to the event handlers generated by the designer.

Тестирование элемента управления Test the control

Поскольку элемент управления DemoCalculator наследуется от класса UserControl, его поведение можно проверить с помощью Контейнера для тестирования пользовательских элементов управления. Because the DemoCalculator control inherits from the UserControl class, you can test its behavior with the UserControl Test Container. Дополнительные сведения см. в разделе Практическое руководство. Тестирование поведения элемента UserControl во время выполнения. For more information, see How to: Test the run-time behavior of a UserControl.

Нажмите клавишу F5, чтобы собрать и запустить элемент управления DemoCalculator в Контейнере для тестирования пользовательских элементов управления. Press F5 to build and run the DemoCalculator control in the UserControl Test Container.

Выберите границу между панелями SplitContainer и перетащите ее влево и вправо. Select the border between the SplitContainer panels and drag it left and right. Размеры элемента TableLayoutPanel и всех его дочерних элементов управления будут изменяться в соответствии с доступным пространством. The TableLayoutPanel and all its child controls resize themselves to fit in the available space.

Завершив тестирование элемента управления, нажмите кнопку Закрыть. When you are finished testing the control, select Close.

Использование элемента управления в форме Use the control on a form

Элемент управления DemoCalculator можно использовать в других составных элементах управления или в форме. The DemoCalculator control can be used in other composite controls or on a form. Ниже описано, как это сделать. The following procedure describes how to use it.

Создание проекта Create the project

Первым шагом является создание проекта приложения. The first step is to create the application project. В этом проекте выполняется сборка приложения, демонстрирующего работу пользовательского элемента управления. You’ll use this project to build the application that shows your custom control.

Создайте проект Приложение Windows Forms с именем DemoCalculatorTest. Create a new Windows Forms Application project and name it DemoCalculatorTest.

В обозревателе решений щелкните правой кнопкой мыши проект DemoCalculatorTest и выберите Добавить ссылку, чтобы открыть диалоговое окно Добавление ссылки. In Solution Explorer, right-click the DemoCalculatorTest project, and then select Add Reference to open the Add Reference dialog box.

Перейдите на вкладку Проекты и выберите проект DemoCalculatorLib, чтобы добавить ссылку на тестовый проект. Go to the Projects tab, and then select the DemoCalculatorLib project to add the reference to the test project.

В обозревателе решений щелкните правой кнопкой мыши DemoCalculatorTest и выберите пункт Назначить запускаемым проектом. In Solution Explorer, right-click DemoCalculatorTest, and then select Set as StartUp Project.

В конструкторе Windows Forms увеличьте размер формы примерно до 700 x 500. In the Windows Forms Designer, increase the size of the form to about 700 x 500.

Использование элемента управления в макете формы Use the control in the form’s layout

Чтобы использовать элемент управления DemoCalculator в приложении, его необходимо поместить в форму. To use the DemoCalculator control in an application, you need to place it on a form.

На панели элементов разверните узел Компоненты DemoCalculatorLib. In Toolbox, expand the DemoCalculatorLib Components node.

Перетащите элемент управления DemoCalculator с панели элементов в форму. Drag the DemoCalculator control from Toolbox onto your form. Переместите элемент управления в левый верхний угол формы. Move the control to the upper-left corner of the form. Когда элемент управления расположен близко к границам формы, отображаются линии привязки. When the control is close to the form’s borders, snaplines will appear. Линии привязки указывают расстояние свойства Padding формы и свойства Margin элемента управления. Snaplines indicate the distance of the form’s Padding property and the control’s Margin property. Поместите элемент управления в расположение, указанное линиями привязки. Position the control at the location indicated by the snaplines.

Перетащите элемент управления Button с панели элементов и поместите его в форму. Drag a Button control from Toolbox and drop it onto the form.

Перемещайте элемент управления Button по элементу управления DemoCalculator, чтобы определить, где отображаются линии привязки. Move the Button control around the DemoCalculator control and observe where the snaplines appear. С помощью этой функции можно точно и легко упорядочить элементы управления. You can align your controls precisely and easily using this feature. По завершении удалите элемент управления Button . Delete the Button control when you’re finished.

Щелкните правой кнопкой мыши элемент управления DemoCalculator и выберите пункт Свойства. Right-click the DemoCalculator control, and then select Properties.

Замените значение свойства Dock на Fill . Change the value of the Dock property to Fill .

Выберите форму, а затем разверните узел свойства Padding . Select the form, and then expand the Padding property node. Замените значение Все на 20. Change the value of All to 20.

Размер элемента управления DemoCalculator уменьшится в соответствии с новым значением формы Padding . The size of the DemoCalculator control is reduced to accommodate the new Padding value of the form.

Измените размер формы, перетаскивая различные маркеры изменения размера в разные положения. Resize the form by dragging the various sizing handles to different positions. Обратите внимание на то, как размер элемента управления DemoCalculator пропорционально изменяется. Observe how the DemoCalculator control is resized to fit.

Следующие шаги Next steps

В этой статье было показано, как создать пользовательский интерфейс для простого калькулятора. This article has demonstrated how to construct the user interface for a simple calculator. В дальнейшем можно расширить его функциональность, реализовав логику калькулятора, а затем опубликовать приложение с помощью ClickOnce. To continue, you can extend its functionality by implementing the calculator logic, then publish the app using ClickOnce. Вы также можете ознакомиться с руководством по созданию средства просмотра рисунков с помощью Windows Forms. Or, continue on to a different tutorial where you create a picture viewer using Windows Forms.

Оцените статью