Properties window in windows form

Свойства элементов управления 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.

Атрибуты в элементах управления 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.

Defining a Property in Windows Forms Controls

For an overview of properties, see Properties Overview. There are a few important considerations when defining a property:

You must apply attributes to the properties you define. Attributes specify how the designer should display a property. For details, see Design-Time Attributes for Components.

Читайте также:  7zip tar gz windows

If changing the property affects the visual display of the control, call the Invalidate method (that your control inherits from Control) from the set accessor. Invalidate in turn calls the OnPaint method, which redraws the control. Multiple calls to Invalidate result in a single call to OnPaint for efficiency.

The .NET Framework class library provides type converters for common data types such as integers, decimal numbers, Boolean values, and others. The purpose of a type converter is generally to provide string-to-value conversion (from string data to other data types). Common data types are associated with default type converters that convert values into strings and strings into the appropriate data types. If you define a property that is a custom (that is, nonstandard) data type, you will have to apply an attribute that specifies the type converter to associate with that property. You can also use an attribute to associate a custom UI type editor with a property. A UI type editor provides a user interface for editing a property or data type. A color picker is an example of a UI type editor. Examples of attributes are given at the end of this topic.

If a type converter or a UI type editor is not available for your custom property, you can implement one as described in Extending Design-Time Support.

The following code fragment defines a custom property named EndColor for the custom control FlashTrackBar .

The following code fragment associates a type converter and a UI type editor with the property Value . In this case Value is an integer and has a default type converter, but the TypeConverterAttribute attribute applies a custom type converter ( FlashTrackBarValueConverter ) that enables the designer to display it as a percentage. The UI type editor, FlashTrackBarValueEditor , allows the percentage to be displayed visually. This example also shows that the type converter or editor specified by the TypeConverterAttribute or EditorAttribute attribute overrides the default converter.

Properties window

Use this window to view and change the design-time properties and events of selected objects that are located in editors and designers. You can also use the Properties window to edit and view file, project, and solution properties. You can find Properties Window on the View menu. You can also open it by pressing F4 or by typing Properties in the search box.

The Properties window displays different types of editing fields, depending on the needs of a particular property. These edit fields include edit boxes, drop-down lists, and links to custom editor dialog boxes. Properties shown in gray are read-only.

UIElement List

Object name
Lists the currently selected object or objects. Only objects from the active editor or designer are visible. When you select multiple objects, only properties common to all selected objects appear.

Categorized
Lists all properties and property values for the selected object, by category. You can collapse a category to reduce the number of visible properties. When you expand or collapse a category, you see a plus (+) or minus (-) to the left of the category name. Categories are listed alphabetically.

Alphabetical
Alphabetically sorts all design-time properties and events for selected objects. To edit an undimmed property, click in the cell to its right and enter changes.

Property Pages
Displays the Property Pages dialog box or Project Designer for the selected item. Property Pages displays a subset, the same or a superset of the properties available in the Properties window. Use this button to view and edit properties related to your project’s active configuration.

Properties
Displays the properties for an object. Many objects also have events that can be viewed using the Properties window.

Sort by Property Source
Groups properties by source, such as inheritance, applied styles, and bindings. Only available when editing XAML files in the designer.

Читайте также:  Что будет если отключить службу windows installer

Events
Displays the events for an object.

This Properties window toolbar control is only available when a form or control designer is active in the context of a Visual C# project. When editing XAML files, events appear on a separate tab of the properties window.

Messages
Lists all Windows messages. Allows you to add or delete specified handler functions for the messages provided for the selected class.

This Properties window toolbar control is only available when Class View is the active window in the context of a Visual C++ project.

Overrides
Lists all virtual functions for the selected class and allows you to add or delete overriding functions.

This Properties window toolbar control is only available when Class View is the active window in the context of a Visual C++ project.

Description pane
Shows the property type and a short description of the property. You can turn the description of the property off and on using the Description command on the shortcut menu.

This Properties window toolbar control is not available when editing XAML files in the designer.

Thumbnail view
Shows a visual representation of the currently selected element when editing XAML files in the designer.

Search
Provides a Search function for properties and events when editing XAML files in the designer. The search box responds to partial word searches and updates search results as you type.

Шаг 3. Настройка свойств формы Step 3: Set your form properties

Далее окно Свойства используется для изменения внешнего вида формы. Next, you use the Properties window to change the way your form looks.

Настройка свойств формы How to set your form properties

Убедитесь, что отображается конструктор Windows Forms. Be sure you’re looking at Windows Forms Designer. В интегрированной среде разработки Visual Studio откройте вкладку Form1.cs [Design] (или вкладку Form1.vb [Design] в Visual Basic). In the Visual Studio integrated development environment (IDE), choose the Form1.cs [Design] tab (or the Form1.vb [Design] tab in Visual Basic).

Чтобы выделить форму Form1, щелкните в любом ее месте. Choose anywhere inside the form Form1 to select it. Посмотрите на окно Свойства. Теперь оно должно отображать свойства формы. Look at the Properties window, which should now be showing the properties for the form. У формы есть различные свойства. Forms have various properties. Например, можно установить цвет переднего плана и фона, текст заголовка, который отображается в верхней части формы, размер формы и другие свойства. For example, you can set the foreground and background color, title text that appears at the top of the form, size of the form, and other properties.

Если окно Свойства не открывается, остановите приложение, нажав квадратную кнопку Остановить отладку на панели инструментов, или просто закройте окно. If the Properties window doesn’t appear, stop your app by choosing the square Stop Debugging button on the toolbar, or just close the window. Если приложение остановлено, но окно Свойства все равно не отображается, в строке меню выберите Вид > Окно свойств. If the app is stopped and you still don’t see the Properties window, on the menu bar, choose View > Properties Window.

Когда форма будет выбрана, найдите свойство Text в окне Свойства. After the form is selected, find the Text property in the Properties window. В зависимости от того, как отсортирован список, может потребоваться прокрутить вниз. Depending on how the list is sorted, you might need to scroll down. Выберите Text, введите Программа просмотра изображений, а затем нажмите клавишу ВВОД. Choose Text, type Picture Viewer, and then choose Enter. Теперь форма должна содержать текст Программа просмотра изображений в заголовке окна. Окно Свойства должно выглядеть так, как показано на снимке экрана ниже. Your form should now have the text Picture Viewer in its title bar, and the Properties window should look similar to the following screenshot.

Читайте также:  Пакет alien astra linux


**Окно* _ _»Свойства» **Properties* _ _window

Свойства можно упорядочить по категориям или в алфавитном порядке. Properties can be ordered by a Categorized or Alphabetical view. Вы можете переключаться между двумя этими представлениями с помощью кнопок в окне Свойства. You can switch between these two views by using the buttons on the Properties window. В этом руководстве свойства легче находить в представлении, в котором свойства представлены в алфавитном порядке. In this tutorial, it’s easier to find properties through the Alphabetical view.

Вернитесь к конструктору Windows Forms. Go back to Windows Forms Designer. Нажмите нижний правый маркер перетаскивания формы, который представляет собой небольшой белый квадрат в нижнем правом углу формы и показан на рисунке ниже. Choose the form’s lower-right drag handle, which is the small white square in the lower-right of the form and appears as follows.


Маркер перетаскивания Drag handle

Перетащите маркер, чтобы изменить размер формы — она должна стать шире и немного выше. Drag the handle to resize the form so the form is wider and a bit taller.

Посмотрите в окно Свойства и обратите внимание, что изменилось значение свойства Size. Look at the Properties window, and notice that the Size property has changed. Свойство Size меняется при каждом изменении формы. The Size property changes each time you resize the form. Перетащите маркер, чтобы форма имела размер около 550, 350 (не обязательно точно такие значения). Такой размер вполне подходит для этого проекта. Try dragging the form’s handle to resize it to a form size of approximately 550, 350 (no need to be exact), which should work well for this project. В качестве альтернативы можно вводить значения непосредственно в свойстве Size и затем нажимать клавишу ВВОД. As an alternative, you can enter the values directly in the Size property and then choose the Enter key.

Запустите приложение еще раз. Run your app again. Помните, что для запуска приложения можно использовать любой из описанных ниже методов. Remember, you can use any of the following methods to run your app.

Нажмите клавишу F5. Choose the F5 key.

В строке меню выберите Отладка > Начать отладку. On the menu bar, choose Debug > Start Debugging.

На панели инструментов нажмите кнопку Начать отладку, которая показана на рисунке ниже. On the toolbar, choose the Start Debugging button, which appears as follows.

**Кнопка «Начать отладку»* _ _на панели инструментов* **Start Debugging* _ _toolbar button*

Как и ранее, интегрированная среда разработки выполняет сборку приложения и запускает его, после чего открывается окно. Just like before, the IDE builds and runs your app, and a window appears.

Перед переходом к следующему шагу остановите приложение, так как интегрированная среда разработки не позволяет изменять выполняющееся приложение. Before going to the next step, stop your app, because the IDE won’t let you change your app while it’s running. Помните, что для остановки приложения можно использовать любой из описанных ниже методов. Remember, you can use any of the following methods to stop your app.

На панели инструментов нажмите кнопку Остановить отладку. On the toolbar, choose the Stop Debugging button.

В строке меню выберите Отладка > Остановить отладку. On the menu bar, choose Debug > Stop Debugging.

На клавиатуре нажмите клавиши SHIFT+F5. Use your keyboard and press Shift+F5.

Нажмите кнопку X в верхнем углу окна Программа просмотра изображений. Choose the X button in the upper corner of the Picture Viewer window.

Дальнейшие действия Next steps

Предыдущий раздел руководства: Шаг 2. Запуск приложения для просмотра изображений. To return to the previous tutorial step, see Step 2: Run your picture viewer app.

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