- Control. Font Свойство
- Определение
- Значение свойства
- Примеры
- Комментарии
- Примечания для тех, кто наследует этот метод
- Как задать текст, отображаемый элементом управления Windows Forms How to: Set the text displayed by a Windows Forms control
- Программный Programmatic
- Designer Designer
- Control Конструкторы
- Определение
- Перегрузки
- Control()
- Комментарии
- Применяется к
- Control(String)
- Параметры
- Комментарии
- Применяется к
- Control(Control, String)
- Параметры
- Комментарии
- Применяется к
- Control(String, Int32, Int32, Int32, Int32)
- Параметры
- Комментарии
- Применяется к
- Control(Control, String, Int32, Int32, Int32, Int32)
- Параметры
- Комментарии
Control. Font Свойство
Определение
Возвращает или задает шрифт текста, отображаемого элементом управления. Gets or sets the font of the text displayed by the control.
Значение свойства
Шрифт Font, применяемый к тексту, отображаемому элементом управления. The Font to apply to the text displayed by the control. Значением по умолчанию является значение свойства DefaultFont. The default is the value of the DefaultFont property.
Примеры
В следующем примере кода выводится FontDialog для пользователя и изменяется Font DateTimePicker элемент управления. The following code example displays a FontDialog to the user and changes the Font of a DateTimePicker control. В этом примере требуется, чтобы в Form Button нем было и DateTimePicker . This example requires that you have a Form with Button and a DateTimePicker on it.
Комментарии
FontСвойство является внешним свойством. The Font property is an ambient property. Внешнее свойство — это свойство элемента управления, которое, если оно не задано, извлекается из родительского элемента управления. An ambient property is a control property that, if not set, is retrieved from the parent control. Например, Button по умолчанию объект будет иметь то же значение, BackColor что и его родительский элемент Form . For example, a Button will have the same BackColor as its parent Form by default. Дополнительные сведения о внешних свойствах см. в разделе AmbientProperties класс или Control Общие сведения о классе. For more information about ambient properties, see the AmbientProperties class or the Control class overview.
Так как объект Font является неизменяемым (то есть вы не можете изменить его свойства), можно назначить только Font новое свойство Font . Because the Font is immutable (meaning that you cannot adjust any of its properties), you can only assign the Font property a new Font. Однако можно создать новый шрифт на основе существующего шрифта. However, you can base the new font on the existing font.
Ниже приведен пример того, как изменить существующий шрифт, сделав его полужирным: The following is an example of how to adjust the existing font to make it bold:
Примечания для тех, кто наследует этот метод
При переопределении Font свойства в производном классе используйте свойство базового класса Font для расширения базовой реализации. When overriding the Font property in a derived class, use the base class’s Font property to extend the base implementation. В противном случае необходимо предоставить всю реализацию. Otherwise, you must provide all the implementation. Переопределение get методов доступа и для свойства не требуется set Font ; при необходимости можно переопределить только одно из них. You are not required to override both the get and set accessors of the Font property; you can override only one if needed.
Как задать текст, отображаемый элементом управления Windows Forms How to: Set the text displayed by a Windows Forms control
Windows Forms элементы управления обычно отображают некоторый текст, связанный с основной функцией элемента управления. Windows Forms controls usually display some text that’s related to the primary function of the control. Например, Button элемент управления обычно отображает заголовок, указывающий, какое действие будет выполнено при нажатии кнопки. For example, a Button control usually displays a caption indicating what action will be performed if the button is clicked. С помощью свойства Text можно задавать или получать текст для всех элементов управления. For all controls, you can set or return the text by using the Text property. Шрифт можно менять с помощью свойства Font. You can change the font by using the Font property.
Можно также задать текст с помощью конструктора. You can also set the text by using the designer.
Программный Programmatic
Присвойте свойству Text строку. Set the Text property to a string.
Чтобы создать подчеркнутый ключ доступа, включает амперсанд (&) перед буквой, которая будет клавишей доступа. To create an underlined access key, includes an ampersand (&) before the letter that will be the access key.
Присвойте свойству Font объект типа Font. Set the Font property to an object of type Font.
Для отображения в элементах пользовательского интерфейса, например пунктах меню, специальных символов, которые обычно интерпретируются в них по-другому, можно использовать escape-символ. You can use an escape character to display a special character in user-interface elements that would normally interpret them differently, such as menu items. Например, следующая строка кода задает текст пункта меню для чтения «& теперь для чего-то совершенно другого»: For example, the following line of code sets the menu item’s text to read «& Now For Something Completely Different»:
Designer Designer
В окне Свойства в Visual Studio задайте для свойства Text элемента управления соответствующую строку. In the Properties window in Visual Studio, set the Text property of the control to an appropriate string.
Чтобы создать подчеркнутую клавишу, она включает амперсанд (&) перед буквой, которая будет клавишей быстрого вызова. To create an underlined shortcut key, includes an ampersand (&) before the letter that will be the shortcut key.
В окне Свойства нажмите кнопку с многоточием ( ) рядом со свойством Font . In the Properties window, select the ellipsis button ( ) next to the Font property.
В диалоговом окне стандартный шрифт выберите шрифт, стиль шрифта, размер, эффекты (например, зачеркивание или подчеркивание) и нужный сценарий. In the standard font dialog box, select the font, font style, size, effects (such as strikeout or underline), and script that you want.
Control Конструкторы
Определение
Инициализирует новый экземпляр класса Control. Initializes a new instance of the Control class.
Перегрузки
Инициализирует новый экземпляр класса Control со значениями по умолчанию. Initializes a new instance of the Control class with default settings.
Инициализирует новый экземпляр класса Control с конкретным текстом. Initializes a new instance of the Control class with specific text.
Инициализирует новый экземпляр класса Control как дочерний элемент управления с конкретным текстом. Initializes a new instance of the Control class as a child control, with specific text.
Инициализирует новый экземпляр класса Control с конкретным текстом, размером и расположением. Initializes a new instance of the Control class with specific text, size, and location.
Инициализирует новый экземпляр класса Control как дочерний элемент управления с определенным текстом, размером и местоположением. Initializes a new instance of the Control class as a child control, with specific text, size, and location.
Control()
Инициализирует новый экземпляр класса Control со значениями по умолчанию. Initializes a new instance of the Control class with default settings.
Комментарии
ControlКласс является базовым классом для всех элементов управления, используемых в Windows Forms приложении. The Control class is the base class for all controls used in a Windows Forms application. Поскольку этот класс обычно не используется для создания экземпляра класса, этот конструктор обычно не вызывается напрямую, а вызывается производным классом. Because this class is not typically used to create an instance of the class, this constructor is typically not called directly but is instead called by a derived class.
Применяется к
Control(String)
Инициализирует новый экземпляр класса Control с конкретным текстом. Initializes a new instance of the Control class with specific text.
Параметры
Текст, отображаемый элементом управления. The text displayed by the control.
Комментарии
ControlКласс является базовым классом для всех элементов управления, используемых в Windows Forms приложении. The Control class is the base class for all controls used in a Windows Forms application. Поскольку этот класс обычно не используется для создания экземпляра класса, этот конструктор обычно не вызывается напрямую, а вызывается производным классом. Because this class is not typically used to create an instance of the class, this constructor is typically not called directly but is instead called by a derived class.
Эта версия Control конструктора задает начальное Text значение свойства для text значения параметра. This version of the Control constructor sets the initial Text property value to the text parameter value.
Применяется к
Control(Control, String)
Инициализирует новый экземпляр класса Control как дочерний элемент управления с конкретным текстом. Initializes a new instance of the Control class as a child control, with specific text.
Параметры
Объект Control, который будет родительским по отношению к элементу управления. The Control to be the parent of the control.
Текст, отображаемый элементом управления. The text displayed by the control.
Комментарии
ControlКласс является базовым классом для всех элементов управления, используемых в Windows Forms приложении. The Control class is the base class for all controls used in a Windows Forms application. Поскольку этот класс обычно не используется для создания экземпляра класса, этот конструктор обычно не вызывается напрямую, а вызывается производным классом. Because this class is not typically used to create an instance of the class, this constructor is typically not called directly but is instead called by a derived class.
Эта версия Control конструктора задает начальное Text значение свойства для text значения параметра. This version of the Control constructor sets the initial Text property value to the text parameter value. Конструктор также добавляет элемент управления в родительский элемент управления Control.ControlCollection . The constructor also adds the control to the parent control’s Control.ControlCollection.
Применяется к
Control(String, Int32, Int32, Int32, Int32)
Инициализирует новый экземпляр класса Control с конкретным текстом, размером и расположением. Initializes a new instance of the Control class with specific text, size, and location.
Параметры
Текст, отображаемый элементом управления. The text displayed by the control.
Позиция X элемента управления относительно левого края контейнера элемента управления (в пикселях). The X position of the control, in pixels, from the left edge of the control’s container. Значение присваивается свойству Left. The value is assigned to the Left property.
Позиция Y элемента управления относительно верхнего края контейнера элемента управления (в пикселях). The Y position of the control, in pixels, from the top edge of the control’s container. Значение присваивается свойству Top. The value is assigned to the Top property.
Ширина элемента управления (в пикселях). The width of the control, in pixels. Значение присваивается свойству Width. The value is assigned to the Width property.
Высота элемента управления (в пикселях). The height of the control, in pixels. Значение присваивается свойству Height. The value is assigned to the Height property.
Комментарии
ControlКласс является базовым классом для всех элементов управления, используемых в Windows Forms приложении. The Control class is the base class for all controls used in a Windows Forms application. Поскольку этот класс обычно не используется для создания экземпляра класса, этот конструктор обычно не вызывается напрямую, а вызывается производным классом. Because this class is not typically used to create an instance of the class, this constructor is typically not called directly but is instead called by a derived class.
Эта версия Control конструктора задает начальное Text значение свойства для text значения параметра. This version of the Control constructor sets the initial Text property value to the text parameter value. Начальная Size и Location для элемента управления определяются left top width height значениями параметров, и. The initial Size and Location of the control are determined by the left , top , width and height parameter values.
Чтобы обеспечить лучшую производительность, не устанавливайте размер элемента управления в конструкторе. To maintain better performance, do not set the size of a control in its constructor. Предпочтительным методом является переопределение DefaultSize Свойства. The preferred method is to override the DefaultSize property.
Применяется к
Control(Control, String, Int32, Int32, Int32, Int32)
Инициализирует новый экземпляр класса Control как дочерний элемент управления с определенным текстом, размером и местоположением. Initializes a new instance of the Control class as a child control, with specific text, size, and location.
Параметры
Объект Control, который будет родительским по отношению к элементу управления. The Control to be the parent of the control.
Текст, отображаемый элементом управления. The text displayed by the control.
Позиция X элемента управления относительно левого края контейнера элемента управления (в пикселях). The X position of the control, in pixels, from the left edge of the control’s container. Значение присваивается свойству Left. The value is assigned to the Left property.
Позиция Y элемента управления относительно верхнего края контейнера элемента управления (в пикселях). The Y position of the control, in pixels, from the top edge of the control’s container. Значение присваивается свойству Top. The value is assigned to the Top property.
Ширина элемента управления (в пикселях). The width of the control, in pixels. Значение присваивается свойству Width. The value is assigned to the Width property.
Высота элемента управления (в пикселях). The height of the control, in pixels. Значение присваивается свойству Height. The value is assigned to the Height property.
Комментарии
ControlКласс является базовым классом для всех элементов управления, используемых в Windows Forms приложении. The Control class is the base class for all controls used in a Windows Forms application. Поскольку этот класс обычно не используется для создания экземпляра класса, этот конструктор обычно не вызывается напрямую, а вызывается производным классом. Because this class is not typically used to create an instance of the class, this constructor is typically not called directly but is instead called by a derived class.
Эта версия Control конструктора задает начальное Text значение свойства для text значения параметра. This version of the Control constructor sets the initial Text property value to the text parameter value. Конструктор также добавляет элемент управления в родительский элемент управления Control.ControlCollection . The constructor also adds the control to the parent control’s Control.ControlCollection. Начальная Size и Location для элемента управления определяются left top width height значениями параметров, и. The initial Size and Location of the control are determined by the left , top , width and height parameter values.
Чтобы обеспечить лучшую производительность, не устанавливайте размер элемента управления в конструкторе. To maintain better performance, do not set the size of a control in its constructor. Предпочтительным методом является переопределение DefaultSize Свойства. The preferred method is to override the DefaultSize property.