Popup. Allows Transparency Свойство
Определение
Возвращает или задает значение, указывающее, может ли элемент управления Popup включать прозрачное содержимое. Gets or sets a value that indicates whether a Popup control can contain transparent content.
Значение свойства
Значение true , если элемент управления Popup может включать прозрачное содержимое; в противном случае — значение false . true if the Popup control can contain transparent content; otherwise, false . Значение по умолчанию — false . The default is false .
Примеры
В следующем примере показано, как задать AllowsTransparency свойство для Popup элемента управления. The following example shows how to set the AllowsTransparency property on a Popup control.
Комментарии
PopupЭлемент управления может содержать только прозрачное содержимое, если приложение выполняется с полным доверием. A Popup control can only contain transparent content when the application runs with full trust. Приложение, работающее с полным доверием, имеет полный доступ к системным ресурсам и обычно устанавливается в локальной системе. An application that runs with full trust has complete access to system resources and is typically installed on the local system. Дополнительные сведения см. в разделе безопасность (WPF). For more information, see Security (WPF).
Это свойство не может иметь значение, true Если Popup размещается в приложении браузера XAML (XBAP). This property cannot be set to true when the Popup is hosted in a XAML browser application (XBAP).
Если AllowsTransparency свойство имеет значение true в приложении, которое не выполняется в режиме полного доверия, AllowsTransparency значение свойства изменяется на false . If the AllowsTransparency property is set to true in an application that does not run in full trust, the AllowsTransparency property value is changed to false . Приложение, размещенное в браузере, является примером приложения, которое не выполняется в режиме полного доверия. An application that is hosted in a browser is an example of an application that does not run in full trust.
ToolTipService и Popup
Настройка свойств ToolTipService
Существуют свойства всплывающих подсказок, которые нельзя задать с помощью свойств класса ToolTip. Для этого предназначен другой класс — ToolTipService. Он позволяет задать длительность задержек при отображении всплывающей подсказки.
Все свойства этого класса являются прикрепленными свойствами, поэтому их можно указывать прямо в дескрипторе элемента управления, как показано ниже:
Класс ToolTipService определяет много тех же свойств, что и класс ToolTip. А это значит, что при работе со всплывающими подсказками, содержащими только текст, можно использовать более простой синтаксис. Вместо добавления вложенного элемента ToolTip, можно задать все, что необходимо, с помощью атрибутов.
InitialShowDelay
Задает задержку (в миллисекундах) перед выводом подсказки после наведения указателя мыши на элемент
ShowDuration
Задает время (в миллисекундах), в течение которого будет отображаться подсказка, если пользователь не сдвинет указатель мыши
BetweenShowDelay
Задает временной интервал (в миллисекундах), в течение которого пользователь может переходить от одной всплывающей подсказки к другой без задержки, определяемой свойством InitialShowDelay. Например, если свойство BetweenShowDelay равно 5000, то у пользователя будет пять секунд на то, чтобы навести указатель мыши на другой элемент управления, у которого имеется всплывающая подсказка. Если пользователь наведет указатель мыши на другой элемент в течение этих пяти секунд, то новая подсказка появится немедленно. Если же пользователь потратит больше пяти секунд, в действие вступит InitialShowDelay. В этом случае вторая подсказка появится после задержки, указанной в свойстве InitialShowDelay.
ToolTip
Задает содержимое всплывающей подсказки. Задание свойства ToolTipService.ToolTip эквивалентно заданию свойства FrameworkElement.ToolTip элемента
HasDropShadow
Определяет, будет ли контекстное окно указателя иметь размытую тень, которая «приподнимает» его над находящимся под ним окном
ShowOnDisabled
Определяет поведение подсказки при отключении базового элемента. Если это свойство имеет значение true, то подсказка будет отображаться для отключенных элементов (т.е. элементов, свойство IsEnabled которых равно false). По умолчанию это свойство равно false, т.е. подсказка отображается только для активных элементов управления
В этом классе определены также два маршрутизируемых события: ToolTipOpening и ToolTipClosing. Реагируя на эти события, можно заполнить окно подсказки актуальным содержимым или переопределить его поведение. Например, если в каждом из этих событий установить флаг handled, подсказки не будут отображаться или скрываться автоматически. Тогда вы сможете выводить и скрывать их вручную с помощью свойства IsOpen.
Не стоит дублировать параметры всплывающих подсказок для нескольких элементов управления. Если вы хотите получить однотипное поведение всплывающих подсказок во всем приложении, используйте стили, чтобы настройки применялись автоматически. К сожалению, значения свойства ToolTipService не наследуются, то есть если задать их на уровне окна или контейнера, они не будут распространяться на вложенные элементы.
Popup
Элемент управления Popup имеет много общего с элементом ToolTip, хотя ни один из них не является наследником другого.
Как и ToolTip, элемент Popup может содержать любой элемент WPF. (Это содержимое хранится в свойстве Popup.Child, а не в свойстве Content, как во всплывающих подсказках.) Как и в элементе ToolTip, содержимое Popup может распространяться за пределы окна. И, наконец, местоположение элемента Popup можно задать с помощью тех же свойств, а показать и скрыть его можно с помощью того же свойства IsOpen.
Но более важны различия между элементами Popup и ToolTip:
Popup не отображается автоматически. Чтобы этот элемент управления отобразился на экране, нужно установить свойство IsOpen.
Свойство Popup.StaysOpen по умолчанию имеет значение true, поэтому элемент управления Popup не исчезнет с экрана до тех пор, пока вы явным образом не присвоите свойству IsOpen значение false. Если присвоить свойству StaysOpen значение false, элемент Popup исчезнет с экрана, как только пользователь щелкнет где-нибудь на экране.
Всплывающее окно, остающееся открытым, может слегка раздражать, т.к. оно ведет себя наподобие отдельного автономного окна. Если сместить указатель мыши, это окно останется в исходной позиции. Такого поведения нет ни у элемента ToolTip, ни у Popup, у которого свойство StaysOpen имеет значение false: как только вы щелкнете кнопкой мыши, чтобы сдвинуть окно, всплывающая подсказка или всплывающее окно исчезнут с экрана.
В классе Popup имеется свойство PopupAnimation, которое позволяет управлять процессом появления окна, когда его свойству IsOpen присваивается значение true. Это свойство может принимать значения None (по умолчанию), Fade (постепенное увеличение непрозрачности), Scroll (непрозрачность плавно распространяется из левого верхнего угла окна) и Slide (окно скользит на свое место). Чтобы активировать любой из этих анимационных эффектов, необходимо, чтобы свойство AllowsTransparency также имело значение true.
Элементы Popup могут принимать фокус. Значит, они могут содержать элементы интерактивной связи с пользователем (например, Button). Эта возможность является одной из ключевых причин использования элемента Popup вместо ToolTip.
Элемент управления Popup определен в пространстве имен System.Windows.Controls.Primitives, так как он чаще всего используется в составе более сложных элементов управления. Элементы Popup не так элегантны, как другие элементы управления. Например, чтобы видеть содержимое, необходимо определить свойство Background, т.к. оно не наследуется от окна. Рамку тоже придется добавлять самостоятельно (для этого очень удобен элемент Border).
Ниже представлен пример использования элемента Popup:
Popup. Placement Свойство
Определение
Возвращает или задает ориентацию элемента управления Popup при его открытии и определяет поведение элемента управления Popup, когда он пересекает границы экрана. Gets or sets the orientation of the Popup control when the control opens, and specifies the behavior of the Popup control when it overlaps screen boundaries.
Значение свойства
Значение из перечисления PlacementMode, определяющее ориентацию элемента управления Popup при его открытии и то, как он взаимодействует с границами экрана. A PlacementMode enumeration value that determines the orientation of the Popup control when the control opens, and that specifies how the control interacts with screen boundaries. Значение по умолчанию — Bottom. The default is Bottom.
Примеры
В следующем примере создаются четыре Popup элемента управления, которые относятся к изображению. The following example creates four Popup controls that are relative to an image. Каждый Popup из них имеет другое значение для свойства размещения. Each Popup has a different value for the placement property.
Комментарии
Если MenuDropAlignment свойство имеет значение true , параметр Placement задает Left или Right изменяет расположение объекта Popup ; объект Popup с Placement установленным значением, равным, Left соответствует левому краю, а параметру PlacementTarget Popup с Placement набору — по Right левому краю PlacementTarget . If the MenuDropAlignment property is true , setting Placement to Left or Right reverses the position of the Popup; a Popup with Placement set to Left aligns its left edge with the right edge of PlacementTarget and a Popup with Placement set to Right aligns its right edge with the left edge of PlacementTarget.
System. Windows. Controls. Primitives Namespace
Contains base classes and controls that are intended to be used as part of other more complex controls.
Classes
Represents a layout control that aligns a bullet and another visual object.
Represents the base class for all Button controls.
Represents a month or year on a Calendar object.
Represents a day on a Calendar.
Represents the currently displayed month or year on a Calendar.
Used within the template of a DataGrid to specify the location in the control’s visual tree where the cells are to be added.
Represents an individual DataGrid column header.
Used within the template of a DataGrid to specify the location in the control’s visual tree where the column headers are to be added.
Used within the template of a DataGrid to specify the location in the control’s visual tree where the row details are to be added.
Represents an individual DataGrid row header.
Used within the template of a DataGrid to specify the location in the control’s visual tree where the rows are to be added.
Represents the text input of a DatePicker.
Represents a viewport for a paginated DocumentPage.
Provides a base class for viewers that are intended to display fixed or flow content (represented by a FixedDocument or FlowDocument, respectively).
Provides information about the DragCompleted event that occurs when a user completes a drag operation with the mouse of a Thumb control.
Provides information about the DragDelta event that occurs one or more times when a user drags a Thumb control with the mouse.
Provides information about the DragStarted event that occurs when a user drags a Thumb control with the mouse.
Represents the base class for classes that define the layout for a row of data where different data items are displayed in different columns.
Provides data for the ItemsChanged event.
Defines methods that provide additional information about the layout state of an element.
Represents a control that defines choices for users to select.
Provides an abstract class for controls that allow multiple items to be selected.
Represents a pop-up window that has content.
Represents an element that has a value within a specific range.
Represents a control that raises its Click event repeatedly from the time it is pressed until it is released.
Represents an implementation of a Thumb control that enables a Window to change its size.
Represents a control that provides a scroll bar that has a sliding Thumb whose position corresponds to a value.
Provides data for a Scroll event that occurs when the Thumb of a ScrollBar moves.
A panel that can hold specified cells in place when the view is scrolled.
Represents a control that allows a user to select items from among its child elements.
Represents a control that displays items and information in a horizontal bar in an application window.
Represents an item of a StatusBar control.
Handles the layout of the TabItem objects on a TabControl.
An abstract base class that provides functionality for text editing controls, including TextBox and RichTextBox.
Represents a control that can be dragged by the user.
Represents a control that draws a set of tick marks for a Slider control.
Base class for controls that can switch states, such as CheckBox.
Used to arrange overflow ToolBar items.
Arranges ToolBar items inside a ToolBar.
Represents a control primitive that handles the positioning and sizing of a Thumb control and two RepeatButton controls that are used to set a Value.
Provides a way to arrange content in a grid where all the cells in the grid have the same size.
Structs
Defines custom placement parameters for a Popup control.
GeneratorPosition is used to describe the position of an item that is managed by ItemContainerGenerator.
Interfaces
Provides a property bag implementation for item panels.
Provides properties through which a control that displays hierarchical data communicates with a VirtualizingPanel.
An interface that is implemented by classes which are responsible for generating user interface (UI) content on behalf of a host.
Extends the IItemContainerGenerator interface to reuse the UI content it generates. Classes that are responsible for generating user interface (UI) content on behalf of a host implement this interface.
Represents the main scrollable region inside a ScrollViewer control.
Enums
Describes the means by which the automatic ToolTip is positioned on a Slider control.
Specifies the direction in which item generation will occur. GeneratorDirection is used by StartAt.
Used by ItemContainerGenerator to indicate the status of its item generation.
Describes the placement of where a Popup control appears on the screen.
Describes how a Popup control animates when it opens.
Describes the direction to move a Popup control to increase the amount of the Popup that is visible.
Describes the behavior that caused a Scroll event for a ScrollBar control.
Specifies the placement of a TickBar with respect to the Track of a Slider control.
Specifies the position of tick marks in a Slider control with respect to the Track that the control implements.
Delegates
Represents a method that provides custom positioning for a Popup control.
Represents a method that will handle the DragCompleted routed event of a Thumb control.
Represents a method that will handle the DragDelta routed event of a Thumb control.
Represents the method that will handle the DragStarted routed event of a Thumb control.
Represents the method that will handle the ItemsChanged event.
Represents the method that will handle the Scroll routed event that occurs when the Thumb of a ScrollBar moves.