WPF-use trigger (13)-trigger

Source: Internet
Author: User

One important thing that WPF provides is binding,
It has helped us to do a lot of things, which we have discussed in this article about binding to WPF learning. For binding, we can set the binding object and link, and verify the input through a certain rule, or
Conversion of values and so on, all of this saves a lot of code that we need to process on our own. For the most important thing about WPF-rendering the UI, of course we must understand and grasp it. The Artist designed
A lot of effects, and design it as a style display (to a large extent, we should think that style is also a resource ), as a programmer, we should not simply use these patchwork effects, according to the program's
The dynamic display of results through logic and user operations is a better way for us to make full use of it for interface rendering. Trigger provides us with a good way to combine these elements.

Trigger
In a sense, it is also a style, because it contains a set of setter and changes the attributes of setter according to one or more conditions. The reason for Reuse
Styles is the best place to place triggers. However, each frameworkelement has a triggers set. You can also put it in the triggers set.
. There are three types of triggers:

· Property trigger: triggered when the value of dependency property changes.

· Data trigger: triggered when the value of the common. Net attribute changes.

· Event trigger: called when the route time is triggered.

1. Property trigger)

 
Property triggers are the most commonly used trigger types in WPF. As we mentioned earlier, dependency properties have the vertical change notification function, so it is very convenient to use property triggers.
More than 2/3 of the attributes are dependency attributes, so they are used in more scenarios. A property trigger triggers a set of setters when the value of a dependency property changes.
The setter set executed by the penalty will be automatically revoked.

For example, when the mouse is placed over the button, the button's appearance changes. Note that attribute triggers are identified by triggers.

<Style X: Key = "buttonmouseover" targettype = "{X: type button}">

      <Style.Triggers>
        <Trigger Property="IsMouseOver" Value="True">
          <Setter Property="RenderTransform">
            <Setter.Value>
              <RotateTransform Angle="10"></RotateTransform>
            </Setter.Value>
          </Setter>
          <Setter Property="RenderTransformOrigin" Value="0.5,0.5"></Setter>
          <Setter Property="Background" Value="#FF0CC030" />
        </Trigger>
      </Style.Triggers>
    </Style>

Attribute triggers are often used for data verification to display verification error messages. In the validation section of the WPF learning binding, we provide an example of using a property trigger to determine whether a verification error exists and display the corresponding verification error message.

<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="300" />
  <Style.Triggers>
    <Trigger Property="Validation.HasError" Value="True">
      <Setter Property="Background" Value="Red"/>
 
       <Setter Property="ToolTip" Value="{Binding
RelativeSource={RelativeSource Self},
Path=(Validation.Errors)[0].ErrorContent}"/>
    </Trigger>
  </Style.Triggers>
</Style>

2. Data trigger datatrigger

Data triggers and attribute triggers have the same object types. A Data trigger is used to trigger and call a set of qualified setters when the value of the custom. Net attribute is changed.

 
The following example shows that in the bound ListBox, if a user object meets certain characteristics (role = admin), the object is highlighted. It is used here.
Datatrigger, because we need to check the role attribute of the user object. This object is a custom non-visualized object and its attribute is a common. Net attribute.

<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. When the attribute role of the bound data is admin, It is highlighted:

<Style TargetType="{x:Type ListBoxItem}">
  <Style.Triggers>
    <DataTrigger Binding="{Binding Path=Role}" Value="Admin">
      <Setter Property="Foreground" Value="Red" />
    </DataTrigger>
  </Style.Triggers>
</Style>

3. Event trigger event trigger

 
An event trigger is called when an event is triggered. Since WPF provides the ability to mark objects and events with XAML, it provides some
Seemingly useless attributes in. NET development, such as ismouseover,
Ispressed and so on. This is used for the purpose of XAML, so that it can easily determine the State through a certain attribute, but also facilitates the property
Trigger application. As an event trigger, what it does and the property
Trigger is similar, but it cannot be a simple set of setter, but must be an instance of triggeraction.

The following example shows how to apply event trigger to change the shadow effect of a button when you click the button.

<Button Margin="15" Width="200" Name="myButton">
      Click Me to Animate Drop Shadow!
      <Button.BitmapEffect>
  
        <!-- This BitmapEffect is 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. 5"
From = "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 = "30" Duration = "0: 0. 5"
Autoreverse = "true"/>
  
<! -- Animate shadow softness of the effect.
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. 5"
Autoreverse = "true"/>
</Storyboard>
</Beginstoryboard>
</Eventtrigger>
</Button. triggers>
</Button>

4. multidatatrigger & multitrigger

 
So far, we have discussed the trigger for a single condition, that is, when a condition is met, it will be triggered. In reality, we may need to trigger a series of operations only when many conditions are met.
You need to use multidatatrigger or multitrigger. Both mutlidatatrigger and multitrigger have
The conditions set is used to store some trigger conditions. Here the relationship between conditions is And. When all conditions are met, the setter set will be called. By name
You can see clearly: multidatatrigger is called when multiple data triggers (only for common. NET attributes) meet the conditions. multitrigger is used to implement
Multiple property triggers are called when the condition is met.

In the following example, only when the iseenabled attribute of the button is true and visible (visibility = visible) is displayed in a conspicuous way. Otherwise, when the isenabled attribute is false, the isenabled attribute is displayed in gray.

<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="14" />
      <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 attribute:

private void Button_Click(object sender, RoutedEventArgs e)
    {
      this.btnVisible.IsEnabled = !this.btnVisible.IsEnabled;
    }

To see the effect (the style on the left when the condition is not met after clicking ):

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

5. Execute user code in the trigger

 
The dependencyproperty. registerattached method allows users to define their own dependency attributes for controls/forms, including callback parameters.
Number can be used to execute a specific method. This allows us to call specific event processing in the trigger. In fact, this is not strictly related to trigger, because it is equivalent
Such as adding custom properties and executing some events. However, trigger can use this benefit to describe the execution business logic:

public
static readonly DependencyProperty SomethingHappenedProperty =
DependencyProperty.RegisterAttached("SomethingHappened", typeof(bool),
typeof(Window1), new PropertyMetadata(false, new
PropertyChangedCallback(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
    }

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.