WPF triggers (not triggers in the database)

Source: Internet
Author: User

First, what is a trigger?
A trigger (Trigger) is a part of a program that completes the corresponding logical function when a condition is met. In the current WPF, there are altogether three types of trigger, which are: (1) property triggers: Their corresponding classes are trigger. It is triggered when a particular associated property has changed. (2) Data trigger: Its corresponding class is DataTrigger. It is triggered when a value recorded by a particular CLR type has changed. (3) Event Trigger: Its corresponding class is EventTrigger. It will be triggered when a particular routed event occurs.

In WPF, there is a triggers property in every class that can use a trigger. The classes that have this attribute are: Frameworkelement,style,datatemplate and ControlTemplate.

Note: The FrameworkElement class only supports EventTrigger. This is because Microsoft has not yet completed its support for the other two types of triggers.

If you need to use the functionality of a property trigger or data trigger in your program, the software developer needs to wrap the trigger one at a time using a method that sets the style trigger, and then apply that style to an instance of the FrameworkElement class. So for now, trigger and EventTrigger can only be used in control templates or styles, and DataTrigger can only be used in data templates. At the same time, in order to support the representation of complex trigger conditions, WPF also introduces MultiTrigger and Multidatatrigger to complete the support for the logic. If you want to use triggers to represent logic, software developers can do so by placing multiple triggers in the Triggers property at the same time.

II. guidelines for use of triggers

Neither of the above triggers can be divorced from the three guidelines that WPF defines for a user interface. These three guidelines not only lead to a trigger being part of WPF, but, more importantly, the definition of the trigger usage specification.

(1) Elemental synthesis

Commonly used, specify TargetType. For example, the advantage of defining a trigger source as a button class instance is that the software handles the left mouse button message for an instance of the image class while processing the mouse left key message of the Button class instance. The effect of element composition on the use of triggers is not only so. In fact, each control in WPF is made up of other interface elements, such as the border,buttonchrome that make up a button control. So when you use XAML to define the appearance of a control, which is the controltemplate of that control, the software developer needs to consider the location of the trigger message source.

(2) interface and behavior separation

A function on an interface that has nothing to do with the business logic of the daemon. As a result, software developers need to use a method in XAML to complete this functionality. The method is to use triggers.

(3) Select the appropriate trigger conditions

In WPF, users can discover a number of seemingly repetitive events and functions. For example, the IInputElement interface has implemented the MouseLeftButtonDown event that represents the left mouse button click, whereas in the ButtonBase class WPF adds the click event for the same behavior. This event not only indicates that the button was pressed by clicking the left click of the mouse, it also means that the default button is pressed when the user presses the ENTER key or the button currently has the input focus when the user presses the SPACEBAR. Another example is that the TextBox class has not only gotfocus this event, but also gotkeyboardfocus,gotstyluscapture and gotmousecapture events. That is, the click event and the GotFocus event are both more powerful events, and it can be expected that there are many such similar cases in various WPF controls. Therefore, when defining triggers in XAML, software developers must consider the actual trigger conditions of the trigger.

Third, the inheritance structure of trigger class

The Triggerbase class is a virtual base class. The class derives directly from the DependencyObject class and introduces only two new properties: Enteractions and Exitactions. These two properties represent the actions to be performed when the property being listened to triggers the current trigger and when it leaves the triggering state. However, because EventTrigger represents a point in time at which an event occurs, rather than a period of time in a certain state, EventTrigger does not support the use of that property. To give EventTrigger the same functionality, WPF adds the Actions property to it.

Example:

<style x:key="Butonstyle"Targettype="Button"> <Style.Triggers> <trigger property="IsMouseOver"Value="True"> <Trigger.EnterActions> <BeginStoryboard> <Storyboard> <doubleanimation storyboard.targetproperty="Opacity"to="0.25"duration="0:0:1"/> </Storyboard> </BeginStoryboard> &L                            T;/trigger.enteractions> <Trigger.ExitActions> <BeginStoryboard> <Storyboard> <doubleanimation Storyboard.TargetProperty ="Opacity"to="1"duration="0:0:1"/> </Storyboard> </BeginStoryboard> &L t;/trigger.exitactions> </Trigger> </Style.Triggers> </Style>

The above pattern indicates that when the mouse moves over, the button becomes opaque, and then gradually returns to its original shape.

Iv. use of setter classes

Setter classes are very easy to use. It has three common properties: Targetname,property and value. These three attributes represent the name of the instance where the property is to be set, the property that needs to be set, and the value that needs to be set. However, it is important to note that the property being set must be an associated property. When TargetType is set in a trigger or style, XAML can directly specify the properties that need to be set and omit the type of the object. However, in the case where no targettype is specified, the setting of the property attribute of the TargetType type in the setter must use the form Targettype.property. For example, a software developer can use the following XAML statement when a setter element is required to set the background color of a button control to blue:

<setter property= "Button.background" value= "Blue"/>
As you can see from MSDN's introduction to the base class setterbase of the setter class, there is not only one derived class for the base class setterbase of the setter class. In addition to the setter class, the derived class of the Setterbase class also has a Eventsetter class. The Eventsetter class is used to complete the definition of an event handler function. For example, if you want a button class instance to run the Onmouseenter function when the mouse moves over it, the software developer can use the following code:
<eventsetter event= "Button.mouseenter" handler= "Onmouseenter"/>

Eventsetter is undoubtedly a less-than-friendly design. And in situations where different eventsetter are used in different places, software developers do not have a good way of judging the sequence in which each event handler is executed. In an event-driven program, it is undoubtedly the most dangerous thing to be able to control the order in which event response functions are executed.

Five, the use of various triggers

1. property triggers

Let's look at the property trigger first. When a property trigger has a specified value on the specified property, it executes the set of other properties that it contains in a series of setter completion. When the property is no longer the specified value, all property settings are restored to the previous state.

Style:
<style x:key="TextBoxStyle1"Targettype="TextBlock"> <Style.Triggers> <trigger property="Text"Value="text"> <setter property="Background"Value="Aqua"/> </Trigger> </Style.Triggers> </Style> applications: <textbloc K Width=" -"style="{StaticResource TextBoxStyle1}"text="text"> </TextBlock>

In the program that contains the example code, if the user enters "text" in the text input box, the background color of the input box turns green. The completion of this control logic is the property trigger trigger defined in the style. In Trigger's declaration, the setting for the trigger property declares the condition that the trigger is triggered: when the Text property is the string "text", the setting of the property in the setter is executed, and the background color is turned green.

4. Data triggers

In addition to the trigger class can be used to listen for changes in properties, software developers can also use DataTrigger to complete the interception of any type of CLR data change. Therefore, the DataTrigger class can not only complete all the functions of the trigger class, but also run the change trigger logic for non-associative properties. The DataTrigger class introduces a total of three parameters: Binding,value and setters. When you need to set the data source that the data trigger listens on, the software developer should do so by assigning a value to the binding property through bindings. That is, if you need to use DataTrigger to complete the change on the face of the textbox background color.

<style x:key="TextBoxStyle2"Targettype="TextBox"> <Style.Triggers> <datatrigger binding="{Binding Relativesource={relativesource self}, path=text}"Value="123"> <setter property="Background"Value="Red"/> </DataTrigger> </Style.Triggers> </Style>

It is important to note that although software developers can use DataTrigger to complete the interception of any CLR type data changes, the setter can only set the associated property. And XAML cannot make changes to the style property in the setter. The reason for this is that a trigger can be defined in a style. How does WPF continue to handle the remaining settings in a trigger when a trigger defined in a style changes the style of its instance? To avoid this problem,WPF prohibits setting styles in triggers.

5. Event triggers

Another type of trigger is available in WPF. The trigger is a trigger condition where an event occurs. The corresponding class for the trigger is EventTrigger, which is the event trigger. This class only adds three properties after deriving from the Triggerbase class: Actions,routedevent and SourceName. A software developer can specify the element name that activates the trigger through the SourceName property. The RoutedEvent property records the event that activates the trigger. Actions is a read-only property that represents the action that needs to be performed when the trigger is triggered.

<eventtrigger routedevent="Mouse.mouseenter"> <EventTrigger.Actions> <BeginStoryboard> <Storyboard> <DoubleAnimation Duration="0:0:0.2"Storyboard.TargetProperty="Width" to=" $"/> </Storyboard> </BeginStoryboard> &L T;/eventtrigger.actions> </EventTrigger>

6. or logical triggers

When a presentation or a logical relationship is required, a software developer can simply tie multiple triggers side by side. When the condition identified by a trigger is satisfied, the behavior that the trigger contains will be executed, causing the properties of the user interface element instance that uses the trigger to change. In the previous example, the software designer not only wanted the background color of the textbox to be green when the user entered "text", but also wanted the background to be "text" in the user's input. Is green, the example is as follows:

<textbox textwrapping="Wrap"margin="5"><textbox.style><style targettype="TextBox"><style.triggers><datatrigger binding="{Binding Relativesource={relativesource self}, path=text}"Value="text"><setter property="Background"Value="Red"/></datatrigger><datatrigger binding="{Binding Relativesource={relativesource self}, path=text}"Value="text."><setter property="Background"Value="Blue"/></datatrigger></style.triggers></style></textbox.style></textbox>

In a logical relationship, each property match of a trigger may be satisfied at the same time. In this case, the trigger will take effect on the state's settings at the same time. When individual triggers conflict with the setting of a property, WPF sets the property according to the rules established by the later declared trigger. As follows:

<button content="Press me!"><button.style><style targettype="{x:type Button}"><style.triggers><trigger property="Button.ismouseover"Value="True"><setter property="Button.foreground"Value="Blue"/></trigger><trigger property="button.ispressed"Value="True"><setter property="Button.foreground"Value="Red"/></trigger></style.triggers></style></button.style></button>

When the user moves the mouse over the button and uses the left button to click on it, the color of the button will be red instead of blue. Because the value of the IsMouseOver property is true before the button is pressed, and the value of the IsPressed property becomes true when the button is pressed, WPF sets the background color of the button to red, as determined by the post-declaration precedence.

7. With logical triggers

If you want to represent a logical relationship, software developers need to use Mutitrigger or Mutidatatrigger. When both triggers are used, the software developer needs to add a trigger condition to their conditions collection. Suppose the software requires the following functionality: When the string that is recorded in the TextBox is "text" and the mouse is over a textbox, the textbox's background color turns green. Examples are as follows:

<textbox textwrapping="Wrap"margin="5"><textbox.style><style targettype="TextBox"><style.triggers><multitrigger><multitrigger.conditions><condition Property="Text"Value="text"/><condition property="IsMouseOver"Value="True"/></multitrigger.conditions><setter property="Background"Value="Aqua"/></multitrigger></style.triggers></style></textbox.style></textbox>

WPF triggers (not triggers in the database)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.