wpf– using triggers

Source: Internet
Author: User

wpf– using triggers

WPF provides a very important thing that binds the binding, which helps us do a lot of things, as we have said in the binding of WPF learning. For the binding we can set its bound object, relationship, and through some rules to verify the input, or the conversion value, etc., behind all this is to save a lot of the code that we need to deal with ourselves. And the most important thing about WPF-The rendering UI-is, of course, something we have to understand and grasp. The artist designs a lot of effects and designs them into styles (to a large extent we should think of style as a resource), and as programmers we should not simply take these patchwork effects, According to the logic of the program and the user's operation to show the dynamic effect is that we can play it to the interface rendering a better way. Trigger provides us with a good way to combine these elements.

A trigger, in a sense it is also a style, because it contains a setter set and performs a property change in the setter based on one or more conditions. For reuse, styles are the best place to put triggers. But for each frameworkelement there are triggers collections, and you can put them in the Triggers collection. There are three types of triggers:

· Attribute Trigger Property Trigger: Triggered when the value of dependency is changed.

· Data Trigger: When normal. NET property is changed when the value of the

· Event Trigger Trigger: Called when the route time is triggered.

1. Attribute trigger (propertyTrigger)

Property triggers are the most common type of triggers in WPF, because we said earlier that dependency properties have the ability to have vertical change notifications, so it is convenient to use property triggers, and because WPF has more than 2/3 properties per control that are dependency properties, it uses more of the occasion. A property trigger is a collection that triggers execution of a setter when the value of a dependency property changes, and when the property loses this value, the set of setter that is executed by the penalty is automatically revoked.

For example, the example below sets the button's appearance to change when hovering over the button. Note that the property trigger is identified with trigger.

<style x:key= "Buttonmouseover" targettype= "{x:type button}" >

<Style.Triggers>

<trigger property= "IsMouseOver" value= "True" >

<setter property= "RenderTransform" >

<Setter.Value>

<rotatetransform angle= "Ten" ></RotateTransform>

</Setter.Value>

</Setter>

<setter property= "Rendertransformorigin" value= "0.5,0.5" ></Setter>

<setter property= "Background" value= "#FF0CC030"/>

</Trigger>

</Style.Triggers>

</Style>

Property triggers are also often used to display validation error messages when validating data. In the validation section of the WPF learning binding we have an example of using a property trigger to determine if there is a validation error and display the appropriate validation error information.

<textbox style= "{StaticResource Validatetextboxstyle}" >

<TextBox.Text>

<binding updatesourcetrigger= "propertychanged" path= "Department" >

<Binding.ValidationRules>

<local:JpgValidationRule/>

</Binding.ValidationRules>

</Binding>

</TextBox.Text>

</TextBox>

.....

<style x:key= "Validatetextboxstyle" targettype= "{x:type TextBox}" >

<setter property= "Width" value= "/>

<Style.Triggers>

<trigger property= "Validation.haserror" value= "True" >

<setter property= "Background" value= "Red"/>

<setter property= "ToolTip" value= "{Binding relativesource={relativesourceself}, Path= (Validation.errors) [0]. Errorcontent} "/>

</Trigger>

</Style.Triggers>

</Style>

2. data trigger Trigger

Data triggers and property triggers are identical except for the object types they face. Data triggers are to detect non-dependent properties------that is, user-defined. NET property-----to trigger and invoke a series of setter collections that meet the criteria.

The following example shows that this object is displayed prominently in a bound listbox if a user object conforms to a certain feature (Role=admin). DataTrigger is used here because we need to detect the attribute role of the user object, which is a custom non-visual object and its properties are normal. Net property.

<Page.Resources>

<clr:users x:key= "Myusers"/>

<datatemplate datatype= "{x:type Clr:user}" >

<textblock text= "{Binding path=name}"/>

</DataTemplate>

...

</Page.Resources>

<StackPanel>

<listbox width= "200"

Itemssource= "{Binding source={staticresource Myusers}}"/>

</StackPanel>

The main part is defined in the style, which is for each listbox item, highlighted when the property of its bound data is role admin:

<style targettype= "{x:type ListBoxItem}" >

<Style.Triggers>

<datatrigger binding= "{Binding path=role}" value= "Admin" >

<setter property= "Foreground" value= "Red"/>

</DataTrigger>

</Style.Triggers>

</Style>

3. Incident Trigger event Trigger

An event trigger, as the name implies, is the action that invokes the trigger when an event is triggered. Because WPF provides the use of XAML to tag objects, events, and so forth, it provides some in common. NET development of seemingly useless properties such as IsMouseOver, ispressed, and so on, which is used for XAML, so that it can be very convenient through a property to determine the state, but also facilitates the use of trigger. As an event trigger, what it does is similar to the property trigger, but its interior cannot be a simple setter set, but must be an instance of TriggerAction.

The following example shows how to apply the event trigger when the mouse button is clicked, so that the shadow effect of the button changes.

<button margin= "width=" name= "MyButton" >

Click Me to Animate Drop shadow!

<Button.BitmapEffect>

<!--This BitmapEffect was targeted by the animation. -

<dropshadowbitmapeffect x:name= "Mydropshadowbitmapeffect" color= "Black" shadowdepth= "0"/>

</Button.BitmapEffect>

<Button.Triggers>

<eventtrigger routedevent= "Button.Click" >

<BeginStoryboard>

<Storyboard>

<!--Animate The movement of the button. -

<thicknessanimation

Storyboard.targetproperty= "Margin" duration= "0:0:0.5"

From= "50,50,50,50" to= "0,0,50,50" autoreverse= "True"/>

<!--Animate Shadow depth of the effect. -

<doubleanimation

Storyboard.targetname= "Mydropshadowbitmapeffect"

Storyboard.targetproperty= "Shadowdepth"

from= "0" to= "duration=" 0:0:0.5 "

autoreverse= "True"/>

<!--Animate Shadow softness of the effect. As

The Button appears to get farther from the shadow,

The shadow gets softer. -

<doubleanimation

Storyboard.targetname= "Mydropshadowbitmapeffect"

storyboard.targetproperty= "Softness"

from= "0" to= "1" duration= "0:0:0.5"

autoreverse= "True"/>

</Storyboard>

</BeginStoryboard>

</EventTrigger>

</Button.Triggers>

</Button>

4. Multidatatrigger & MultiTrigger

So far we've been talking about triggers for a single condition, which means that when a condition is met, it is triggered. In reality, we may need to meet a number of conditions to trigger a series of operations, this time we need to use Multidatatrigger or MultiTrigger. Both Mutlidatatrigger and MultiTrigger have a conditions set to hold some trigger conditions, where the condition is the relationship between and, and the setter collection is called when all the conditions are met. According to the name you can see clearly: Multidatatrigger is used to implement multiple data triggers (only for normal. NET properties) when the condition is met, and MultiTrigger is used to implement multiple property triggers (for dependency properties) when the condition is met.

The following example displays the Iseenabled property of the button only if it is true and is visible (visibility=visible), otherwise it is grayed out when the IsEnabled property is false.

<style targettype= "{x:type button}" x:key= "Highlightstyle" >

<Style.Triggers>

<trigger property= "IsEnabled" value= "false" >

<setter property= "Background" value= "#EEEEEE"/>

</Trigger>

<MultiTrigger>

<MultiTrigger.Conditions>

<condition property= "Visibility" value= "Visible"/>

<condition property= "IsEnabled" value= "true"/>

</MultiTrigger.Conditions>

<setter property= "BorderBrush" value= "Red"/>

<setter property= "FontSize" value= "/>"

<setter property= "FontWeight" value= "Bold"/>

<setter property= "Foreground" value= "Red"/>

</MultiTrigger>

</Style.Triggers>

</Style>

...

<button style= "{StaticResource highlightstyle}" content= "Hight Value" x:name= "btnvisible" click= "Button_Click"/ >

Add a Click event to the button to change the IsEnabled property:

private void Button_Click (object sender, RoutedEventArgs e)

{

this.btnVisible.IsEnabled =!this.btnvisible.isenabled;

}

Look at the effect (the left side is a style that does not meet the criteria when clicked):

Similarly, you can use Multidatatrigger to perform multi-conditional and relational operations on custom attributes.

5. Executing user code in triggers

The Dependencyproperty.registerattached method allows the user to define its own dependency property for a control/form, etc., which contains a callback parameter that allows a particular method to be executed. This allows us to invoke specific event handling in the trigger. In fact, strictly speaking this is not very related to trigger, because it is equivalent to adding a custom attribute to an object and executing some events. But trigger can take advantage of this benefit to profile the execution of business logic:

public static readonly DependencyProperty somethinghappenedproperty =dependencyproperty.registerattached (" Somethinghappened ", typeof (BOOL), typeof (Window1), new PropertyMetadata (False, Newpropertychangedcallback ( (somethinghappened)));

public bool Getsomethinghappened (DependencyObject D)

{

return (BOOL) d.getvalue (Somethinghappenedproperty);

}

public void setsomethinghappened (DependencyObject D, bool value)

{

D.setvalue (somethinghappenedproperty, value);

}

public static void somethinghappened (DependencyObject D,dependencypropertychangedeventargs e)

{

Do something here

}

wpf– using triggers

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.