Windows forms image buttons

Xamarin.Forms ImageButton Xamarin.Forms ImageButton

Элемент ImageButton отображает изображение и реагирует на касание или щелчок, который направляет приложение для выполнения определенной задачи. The ImageButton displays an image and responds to a tap or click that directs an application to carry out a particular task.

ImageButton Представление объединяет Button представление и Image представление для создания кнопки, содержимое которой является изображением. The ImageButton view combines the Button view and Image view to create a button whose content is an image. Пользователь нажимает ImageButton с помощью пальца или щелкает его с помощью мыши, чтобы направить приложение на выполнение определенной задачи. The user presses the ImageButton with a finger or clicks it with a mouse to direct the application to carry out a particular task. Однако, в отличие от Button представления, ImageButton представление не имеет концепции текста и внешнего вида текста. However, unlike the Button view, the ImageButton view has no concept of text and text appearance.

Пока Button представление определяет Image свойство, которое позволяет отображать изображение в Button , это свойство предназначено для использования при отображении маленького значка рядом с Button текстом. While the Button view defines an Image property, that allows you to display a image on the Button , this property is intended to be used when displaying a small icon next to the Button text.

Примеры кода из этого руководств взяты из примера формсгаллери. The code examples in this guide are taken from the FormsGallery sample.

Задание источника изображения Setting the image source

ImageButton Определяет Source свойство, которое должно быть задано для изображения, отображаемого на кнопке, в качестве источника изображения — файл, URI, ресурс или поток. ImageButton defines a Source property that should be set to the image to display in the button, with the image source being either a file, a URI, a resource, or a stream. Дополнительные сведения о загрузке изображений из разных источников см. в разделе изображения Xamarin.Forms в . For more information about loading images from different sources, see Images in Xamarin.Forms.

В следующем примере показано, как создать экземпляр ImageButton в XAML: The following example shows how to instantiate a ImageButton in XAML:

Source Свойство определяет изображение, которое отображается в ImageButton . The Source property specifies the image that appears in the ImageButton . В этом примере задается локальный файл, который будет загружен из каждого проекта платформы, в результате чего будут отображены следующие снимки экрана: In this example it’s set to a local file that will be loaded from each platform project, resulting in the following screenshots:

По умолчанию ImageButton является прямоугольным, но можно передать скругленные углы с помощью CornerRadius Свойства. By default, the ImageButton is rectangular, but you can give it rounded corners by using the CornerRadius property. Дополнительные сведения о ImageButton внешнем представлении см. в разделе представление ImageButton. For more information about ImageButton appearance, see ImageButton appearance.

Хотя ImageButton может загрузить анимированный GIF-файл, он будет отображать только первый кадр GIF-файла. While an ImageButton can load an animated GIF, it will only display the first frame of the GIF.

Читайте также:  Настройка майл почты windows

В следующем примере показано, как создать страницу, которая функционально эквивалентна предыдущему примеру XAML, но полностью в C#: The following example shows how to create a page that is functionally equivalent to the previous XAML example, but entirely in C#:

Обработка щелчков ImageButton Handling ImageButton clicks

ImageButton Определяет Clicked событие, возникающее при касании пользователем ImageButton пальцем или указателем мыши. ImageButton defines a Clicked event that is fired when the user taps the ImageButton with a finger or mouse pointer. Событие возникает при отпускании кнопки с пальцем или кнопкой мыши с поверхности ImageButton . The event is fired when the finger or mouse button is released from the surface of the ImageButton . Свойство должно иметь значение, равное, чтобы ImageButton IsEnabled true реагировать на касания. The ImageButton must have its IsEnabled property set to true to respond to taps.

В следующем примере показано, как создать экземпляр ImageButton в XAML и обменять его Clicked событие: The following example shows how to instantiate a ImageButton in XAML and handle its Clicked event:

Clicked Для события задается обработчик событий с именем OnImageButtonClicked , который находится в файле кода программной части: The Clicked event is set to an event handler named OnImageButtonClicked that is located in the code-behind file:

При касании ImageButton выполняется метод OnImageButtonClicked . When the ImageButton is tapped, the OnImageButtonClicked method executes. sender Аргумент является ImageButton ответственным за это событие. The sender argument is the ImageButton responsible for this event. Его можно использовать для доступа к ImageButton объекту или для различения нескольких объектов, ImageButton совместно использующих одно и то же Clicked событие. You can use this to access the ImageButton object, or to distinguish between multiple ImageButton objects sharing the same Clicked event.

Этот конкретный Clicked обработчик увеличивает счетчик и отображает значение счетчика в Label : This particular Clicked handler increments a counter and displays the counter value in a Label :

В следующем примере показано, как создать страницу, которая функционально эквивалентна предыдущему примеру XAML, но полностью в C#: The following example shows how to create a page that is functionally equivalent to the previous XAML example, but entirely in C#:

Отключение ImageButton Disabling the ImageButton

Иногда приложение находится в определенном состоянии, в котором конкретный ImageButton щелчок не является допустимой операцией. Sometimes an application is in a particular state where a particular ImageButton click is not a valid operation. В таких случаях ImageButton следует отключить, задав IsEnabled свойству значение false . In those cases, the ImageButton should be disabled by setting its IsEnabled property to false .

Использование интерфейса команд Using the command interface

Приложение может реагировать на ImageButton касания без обработки Clicked события. It is possible for an application to respond to ImageButton taps without handling the Clicked event. ImageButton Класс реализует альтернативный механизм уведомления, называемый командой или интерфейсом командной строки . The ImageButton implements an alternative notification mechanism called the command or commanding interface. Это состоит из двух свойств: This consists of two properties:

  • Command типа ICommand — интерфейс, определенный в System.Windows.Input пространстве имен. Command of type ICommand , an interface defined in the System.Windows.Input namespace.
  • CommandParameter свойство типа Object . CommandParameter property of type Object .

Этот подход подходит для связи с привязкой данных, особенно при реализации архитектуры Model-View-ViewModel (MVVM). This approach is suitable in connection with data-binding, and particularly when implementing the Model-View-ViewModel (MVVM) architecture.

Дополнительные сведения об использовании интерфейса командной строки см . в разделе Использование интерфейса команды в этой панели. For more information about using the command interface, see Using the command interface in the Button guide.

Читайте также:  Своя сборка linux live

Нажатие и освобождение ImageButton Pressing and releasing the ImageButton

Помимо события Clicked«ImageButton также определяет события Pressed и Released . Besides the Clicked event, ImageButton also defines Pressed and Released events. Это Pressed событие возникает, когда палец нажимает на ImageButton , или кнопка мыши нажата с указателем, расположенным над ImageButton . The Pressed event occurs when a finger presses on a ImageButton , or a mouse button is pressed with the pointer positioned over the ImageButton . Это Released событие возникает при отпускании кнопки мыши или пальца. The Released event occurs when the finger or mouse button is released. Как правило, Clicked событие также срабатывает в то же время, что и Released событие, но если палец или указатель мыши выходят за пределы области ImageButton до выпуска, Clicked событие может не произойти. Generally, the Clicked event is also fired at the same time as the Released event, but if the finger or mouse pointer slides away from the surface of the ImageButton before being released, the Clicked event might not occur.

Дополнительные сведения об этих событиях см. в разделе, посвященном нажатию и отпустите кнопку в данной панели . For more information about these events, see Pressing and releasing the button in the Button guide.

Вид ImageButton ImageButton appearance

В дополнение к свойствам, ImageButton унаследованным от View класса, ImageButton также определяет несколько свойств, влияющих на его внешний вид: In addition to the properties that ImageButton inherits from the View class, ImageButton also defines several properties that affect its appearance:

  • Aspect показывает, как изображение будет масштабироваться в соответствии с отображаемой областью. Aspect is how the image will be scaled to fit the display area.
  • BorderColor цвет области, окружающей ImageButton . BorderColor is the color of an area surrounding the ImageButton .
  • BorderWidth Ширина границы. BorderWidth is the width of the border.
  • CornerRadius Радиус угла ImageButton . CornerRadius is the corner radius of the ImageButton .

Aspect Свойству может быть присвоено одно из членов Aspect перечисления: The Aspect property can be set to one of the members of the Aspect enumeration:

  • Fill — растягивает изображение до полного и точного заполнения ImageButton . Fill — stretches the image to completely and exactly fill the ImageButton . Это может привести к искажению изображения. This may result in the image being distorted.
  • AspectFill — обрезает изображение таким образом, чтобы оно заполнило с ImageButton сохранением пропорций. AspectFill — clips the image so that it fills the ImageButton while preserving the aspect ratio.
  • AspectFit -леттербоксес изображение (при необходимости), чтобы весь образ поместился в ImageButton , с добавлением пробела в верхнюю или нижнюю часть или в зависимости от того, является ли изображение широким или максимальным. AspectFit — letterboxes the image (if necessary) so that the entire image fits into the ImageButton , with blank space added to the top/bottom or sides depending on whether the image is wide or tall. Это значение перечисления по умолчанию Aspect . This is the default value of the Aspect enumeration.

ImageButton Класс также имеет Margin Свойства и Padding , управляющие поведением макета ImageButton . The ImageButton class also has Margin and Padding properties that control the layout behavior of the ImageButton . Дополнительные сведения см. в статье Поля и заполнение. For more information, see Margin and Padding.

Визуальные состояния ImageButton ImageButton visual states

ImageButton имеет объект Pressed VisualState , который можно использовать для инициации визуального изменения в ImageButton при нажатии пользователем, при условии, что он включен. ImageButton has a Pressed VisualState that can be used to initiate a visual change to the ImageButton when pressed by the user, provided that it’s enabled.

Читайте также:  Назначение диалоговых окон windows

В следующем примере XAML показано, как определить визуальное состояние для Pressed состояния: The following XAML example shows how to define a visual state for the Pressed state:

Pressed VisualState Указывает, что при ImageButton нажатии элемента его Scale свойство будет заменено значением по умолчанию от 1 до 0,8. The Pressed VisualState specifies that when the ImageButton is pressed, its Scale property will be changed from its default value of 1 to 0.8. Normal VisualState Указывает, что если ImageButton находится в нормальном состоянии, его Scale свойство будет установлено в значение 1. The Normal VisualState specifies that when the ImageButton is in a normal state, its Scale property will be set to 1. Таким образом, общий результат заключается в том, что при ImageButton нажатии кнопки она масштабируется немного меньше, а при ImageButton освобождении она масштабируется до размера по умолчанию. Therefore, the overall effect is that when the ImageButton is pressed, it’s rescaled to be slightly smaller, and when the ImageButton is released, it’s rescaled to its default size.

Элемент управления Button (Windows Forms) Button Control (Windows Forms)

Элемент управления Windows Forms Button позволяет пользователю щелкнуть его для выполнения действия. The Windows Forms Button control allows the user to click it to perform an action. На элементе управления Button могут отображаться текст и изображения. The Button control can display both text and images. При щелчке кнопки мышью элемент управления выглядит так, как будто его нажимают и отпускают. When the button is clicked, it looks as if it is being pushed in and released.

в этом разделе In This Section

Общие сведения об элементе управления Button Button Control Overview
Описание элемента управления, его основных возможностей и свойств. Explains what this control is and its key features and properties.

Практическое руководство. Обработка события нажатия кнопки в Windows Forms How to: Respond to Windows Forms Button Clicks
Описание основных приемов использования кнопки на форме Windows Forms. Explains the most basic use of a button on a Windows Form.

Практическое руководство. Назначение кнопок принятия в Windows Forms How to: Designate a Windows Forms Button as the Accept Button
Описывается, как назначить элемент управления Button в качестве кнопки «Принять», также известной как кнопка по умолчанию. Explains how to designate a Button control to be the accept button, also known as the default button.

Практическое руководство. Назначение кнопок отмены в Windows Forms How to: Designate a Windows Forms Button as the Cancel Button
Описывается, как назначить элемент управления Button в качестве кнопки «Отмена», которая активируется при любом нажатии клавиши ESC. Explains how to designate a Button control to be the cancel button, which is clicked whenever the user presses the ESC key.

Справочник Reference

Класс Button Button class
Описание класса и всех его членов. Describes this class and has links to all its members.

Элементы управления для использования в формах Windows Forms Controls to Use on Windows Forms
Полный список элементов управления Windows Forms со ссылками на информацию об их применении. Provides a complete list of Windows Forms controls, with links to information on their use.

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