Wpf system windows controls control

Controls

Windows Presentation Foundation (WPF) ships with many of the common UI components that are used in almost every Windows application, such as Button, Label, TextBox, Menu, and ListBox. Historically, these objects have been referred to as controls. While the WPF SDK continues to use the term «control» to loosely mean any class that represents a visible object in an application, it is important to note that a class does not need to inherit from the Control class to have a visible presence. Classes that inherit from the Control class contain a ControlTemplate, which allows the consumer of a control to radically change the control’s appearance without having to create a new subclass. This topic discusses how controls (both those that do inherit from the Control class and those that do not) are commonly used in WPF.

Creating an Instance of a Control

You can add a control to an application by using either Extensible Application Markup Language (XAML) or code. The following example shows how to create a simple application that asks a user for their first and last name. This example creates six controls: two labels, two text boxes, and two buttons, in XAML. All controls can be created similarly.

The following example creates the same application in code. For brevity, the creation of the Grid, grid1 , has been excluded from the sample. grid1 has the same column and row definitions as shown in the preceding XAML example.

Changing the Appearance of a Control

It is common to change the appearance of a control to fit the look and feel of your application. You can change the appearance of a control by doing one of the following, depending on what you want to accomplish:

Change the value of a property of the control.

Create a Style for the control.

Create a new ControlTemplate for the control.

Changing a Control’s Property Value

Many controls have properties that allow you to change how the control appears, such as the Background of a Button. You can set the value properties in both XAML and code. The following example sets the Background, FontSize, and FontWeight properties on a Button in XAML.

The following example sets the same properties in code.

Creating a Style for a Control

WPF gives you the ability to specify the appearance of controls wholesale, instead of setting properties on each instance in the application, by creating a Style. The following example creates a Style that is applied to each Button in the application. Style definitions are typically defined in XAML in a ResourceDictionary, such as the Resources property of the FrameworkElement.

You can also apply a style to only certain controls of a specific type by assigning a key to the style and specifying that key in the Style property of your control. For more information about styles, see Styling and Templating.

Creating a ControlTemplate

A Style allows you to set properties on multiple controls at a time, but sometimes you might want to customize the appearance of a Control beyond what you can do by creating a Style. Classes that inherit from the Control class have a ControlTemplate, which defines the structure and appearance of a Control. The Template property of a Control is public, so you can give a Control a ControlTemplate that is different than its default. You can often specify a new ControlTemplate for a Control instead of inheriting from a control to customize the appearance of a Control.

Consider the very common control, Button. The primary behavior of a Button is to enable an application to take some action when the user clicks it. By default, the Button in WPF appears as a raised rectangle. While developing an application, you might want to take advantage of the behavior of a Button—that is, by handling the button’s click event—but you might change the button’s appearance beyond what you can do by changing the button’s properties. In this case, you can create a new ControlTemplate.

Читайте также:  Как выполнить диагностику сети windows

The following example creates a ControlTemplate for a Button. The ControlTemplate creates a Button with rounded corners and a gradient background. The ControlTemplate contains a Border whose Background is a LinearGradientBrush with two GradientStop objects. The first GradientStop uses data binding to bind the Color property of the GradientStop to the color of the button’s background. When you set the Background property of the Button, the color of that value will be used as the first GradientStop. For more information about data binding, see Data Binding Overview. The example also creates a Trigger that changes the appearance of the Button when IsPressed is true .

The Background property of the Button must be set to a SolidColorBrush for the example to work properly.

Subscribing to Events

You can subscribe to a control’s event by using either XAML or code, but you can only handle an event in code. The following example shows how to subscribe to the Click event of a Button.

The following example handles the Click event of a Button.

Rich Content in Controls

Most classes that inherit from the Control class have the capacity to contain rich content. For example, a Label can contain any object, such as a string, an Image, or a Panel. The following classes provide support for rich content and act as base classes for most of the controls in WPF.

ContentControl— Some examples of classes that inherit from this class are Label, Button, and ToolTip.

ItemsControl— Some examples of classes that inherit from this class are ListBox, Menu, and StatusBar.

HeaderedContentControl— Some examples of classes that inherit from this class are TabItem, GroupBox, and Expander.

HeaderedItemsControl—Some examples of classes that inherit from this class are MenuItem, TreeViewItem, and ToolBar.

For more information about these base classes, see WPF Content Model.

Элементы управления Controls

Windows Presentation Foundation (WPF) Windows Presentation Foundation (WPF) содержит большинство распространенных компонентов пользовательского интерфейса, которые используются практически во всех приложениях Windows, например, Button, Label, TextBox, Menu и ListBox. Windows Presentation Foundation (WPF) Windows Presentation Foundation (WPF) ships with many of the common UI components that are used in almost every Windows application, such as Button, Label, TextBox, Menu, and ListBox. Исторически эти объекты называются элементами управления. Historically, these objects have been referred to as controls. Хотя в SDK WPF WPF продолжает использоваться термин «элемент управления» для обобщенного обозначения любого класса, представляющего видимый объект в приложении, важно отметить, что класс не обязательно должен наследоваться от класса Control, чтобы иметь визуальное представление. While the WPF WPF SDK continues to use the term «control» to loosely mean any class that represents a visible object in an application, it is important to note that a class does not need to inherit from the Control class to have a visible presence. Классы, наследуемые от класса Control, содержат шаблон ControlTemplate, который позволяет существенно изменить внешний вид элемента управления, не создавая новый подкласс. Classes that inherit from the Control class contain a ControlTemplate, which allows the consumer of a control to radically change the control’s appearance without having to create a new subclass. В этой статье описаны типичные методы применения элементов управления (которые наследуются или не наследуются от класса Control) в WPF WPF . This topic discusses how controls (both those that do inherit from the Control class and those that do not) are commonly used in WPF WPF .

Создание экземпляра элемента управления Creating an Instance of a Control

Элемент управления можно добавить в приложение с помощью Язык XAML Extensible Application Markup Language (XAML) или кода. You can add a control to an application by using either Язык XAML Extensible Application Markup Language (XAML) or code. В следующем примере показано, как создать простое приложение, которое запрашивает у пользователя имя и фамилию. The following example shows how to create a simple application that asks a user for their first and last name. В этом примере создается шесть элементов управления: две метки, два текстовых поля и две кнопки на XAML XAML . This example creates six controls: two labels, two text boxes, and two buttons, in XAML XAML . Все элементы управления могут быть созданы аналогичным образом. All controls can be created similarly.

Читайте также:  Windows как посмотреть список устройств подключенных по usb

В следующем примере создается такое же приложение в коде. The following example creates the same application in code. Для упрощения примера из него исключено создание Grid, grid1 . For brevity, the creation of the Grid, grid1 , has been excluded from the sample. grid1 имеет такие же определения столбцов и строк, как показано в предыдущем примере XAML XAML . grid1 has the same column and row definitions as shown in the preceding XAML XAML example.

Изменение внешнего вида элемента управления Changing the Appearance of a Control

Обычно внешний вид элемента управления изменяется в соответствии с внешним видом приложения. It is common to change the appearance of a control to fit the look and feel of your application. Можно изменить внешний вид элемента управления, выполнив одно из следующих действий (в зависимости от того, чего нужно достичь): You can change the appearance of a control by doing one of the following, depending on what you want to accomplish:

Измените значение свойства элемента управления. Change the value of a property of the control.

Создайте Style для элемента управления. Create a Style for the control.

Создайте новый ControlTemplate для элемента управления. Create a new ControlTemplate for the control.

Изменение значения свойства элемента управления Changing a Control’s Property Value

У многих элементов управления есть свойства, которые позволяют изменять внешний вид элемента управления, например, Background для Button. Many controls have properties that allow you to change how the control appears, such as the Background of a Button. Значения свойства можно задать как на XAML XAML , так и в коде. You can set the value properties in both XAML XAML and code. В следующем примере устанавливаются свойства Background, FontSize и FontWeight для Button на XAML XAML . The following example sets the Background, FontSize, and FontWeight properties on a Button in XAML XAML .

Следующий пример устанавливает те же самые свойства в коде. The following example sets the same properties in code.

Создание стиля для элемента управления Creating a Style for a Control

WPF WPF позволяет управлять внешним видом всех элементов, создавая Style, вместо того чтобы указывать свойства отдельно для каждого экземпляра в приложении. gives you the ability to specify the appearance of controls wholesale, instead of setting properties on each instance in the application, by creating a Style. В следующем примере создается Style, который применяется к каждому объекту Button в приложении. The following example creates a Style that is applied to each Button in the application. Определения Style обычно задаются на XAML XAML для ResourceDictionary, например, в свойстве Resources объекта FrameworkElement. Style definitions are typically defined in XAML XAML in a ResourceDictionary, such as the Resources property of the FrameworkElement.

Можно также применить стиль только к определенным элементам управления конкретного типа, присвоив ключ стилю и указав этот ключ в свойстве Style элемента управления. You can also apply a style to only certain controls of a specific type by assigning a key to the style and specifying that key in the Style property of your control. Дополнительные сведения о стилях см. в статье Стили и шаблоны в WPF. For more information about styles, see Styling and Templating.

Создание шаблона ControlTemplate Creating a ControlTemplate

Style позволяет задать свойства для нескольких элементов управления одновременно, но иногда для настройки внешнего вида Control вам потребуется больше возможностей, чем предоставляет создание Style. A Style allows you to set properties on multiple controls at a time, but sometimes you might want to customize the appearance of a Control beyond what you can do by creating a Style. Классы, которые наследуются от класса Control, имеют ControlTemplate, который определяет структуру и внешний вид Control. Classes that inherit from the Control class have a ControlTemplate, which defines the structure and appearance of a Control. Свойство Template для Control является открытым, поэтому пользователь может указать для Control значение ControlTemplate, отличное от значения по умолчанию. The Template property of a Control is public, so you can give a Control a ControlTemplate that is different than its default. Обычно для настройки внешнего вида Control можно указать новый ControlTemplate для Control, а не наследовать свойства элемента управления. You can often specify a new ControlTemplate for a Control instead of inheriting from a control to customize the appearance of a Control.

Давайте рассмотрим очень популярный элемент управления Button. Consider the very common control, Button. Основное назначение Button — предоставить приложению возможность выполнить определенное действие, когда пользователь нажимает кнопку. The primary behavior of a Button is to enable an application to take some action when the user clicks it. По умолчанию Button в WPF WPF отображается как объемный прямоугольник. By default, the Button in WPF WPF appears as a raised rectangle. При разработке приложения вас обычно интересует поведение Button, то есть обработка события нажатия кнопки, но вы можете изменить еще и внешний вид кнопки, не ограничиваясь стандартными свойствами кнопки. While developing an application, you might want to take advantage of the behavior of a Button—that is, by handling the button’s click event—but you might change the button’s appearance beyond what you can do by changing the button’s properties. В нашем примере создается новый ControlTemplate. In this case, you can create a new ControlTemplate.

Читайте также:  Windows создана папка загрузки

В следующем примере создается ControlTemplate для Button. The following example creates a ControlTemplate for a Button. ControlTemplate создает Button со скругленными углами и градиентным фоном. The ControlTemplate creates a Button with rounded corners and a gradient background. ControlTemplate содержит Border, у которого Background является LinearGradientBrush с двумя объектами GradientStop. The ControlTemplate contains a Border whose Background is a LinearGradientBrush with two GradientStop objects. Первый GradientStop использует привязку данных, чтобы связать свойство Color объекта GradientStop с цветом фона кнопки. The first GradientStop uses data binding to bind the Color property of the GradientStop to the color of the button’s background. Когда вы изменяете свойство Background объекта Button, соответствующий новому значению цвет будет использоваться как первый GradientStop. When you set the Background property of the Button, the color of that value will be used as the first GradientStop. Дополнительные сведения о привязке данных см. в разделе Общие сведения о привязке данных. For more information about data binding, see Data Binding Overview. Также в этом примере создается Trigger, который изменяет внешний вид Button, если IsPressed имеет значение true . The example also creates a Trigger that changes the appearance of the Button when IsPressed is true .

Чтобы наш пример работал правильно, свойство Background для Button должно иметь значение SolidColorBrush. The Background property of the Button must be set to a SolidColorBrush for the example to work properly.

Подписка на события Subscribing to Events

Можно подписаться на событие элемента управления с помощью XAML XAML или кода, но обрабатывать события можно только в коде. You can subscribe to a control’s event by using either XAML XAML or code, but you can only handle an event in code. Следующий пример демонстрирует, как подписаться на событие Click объекта Button. The following example shows how to subscribe to the Click event of a Button.

Следующий пример демонстрирует, как обрабатывать событие Click объекта Button. The following example handles the Click event of a Button.

Форматированное содержимое в элементах управления Rich Content in Controls

Большинство классов, которые наследуются от класса Control, могут содержать форматированное содержимое. Most classes that inherit from the Control class have the capacity to contain rich content. Например, Label может содержать любой объект, Image или Panel. For example, a Label can contain any object, such as a string, an Image, or a Panel. Следующие классы обеспечивают поддержку форматированного содержимого и служат базовыми классами для большинства элементов управления в WPF WPF . The following classes provide support for rich content and act as base classes for most of the controls in WPF WPF .

ContentControl — в качестве примеров классов, которые наследуются от этого класса, можно назвать Label, Button, и ToolTip. ContentControl— Some examples of classes that inherit from this class are Label, Button, and ToolTip.

ItemsControl — в качестве примеров классов, которые наследуются от этого класса, можно назвать ListBox, Menu, и StatusBar. ItemsControl— Some examples of classes that inherit from this class are ListBox, Menu, and StatusBar.

HeaderedContentControl — в качестве примеров классов, которые наследуются от этого класса, можно назвать TabItem, GroupBox, и Expander. HeaderedContentControl— Some examples of classes that inherit from this class are TabItem, GroupBox, and Expander.

HeaderedItemsControl — в качестве примеров классов, которые наследуются от этого класса, можно назвать MenuItem, TreeViewItem, и ToolBar. HeaderedItemsControl—Some examples of classes that inherit from this class are MenuItem, TreeViewItem, and ToolBar.

Для получения дополнительной информации об этих базовых классах см. раздел Модель содержимого WPF. For more information about these base classes, see WPF Content Model.

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