WPF 中有哪些不同的触发器?

发布于 2024-08-21 04:50:43 字数 183 浏览 1 评论 0原文

WPF 中有哪些不同的触发器?它们有何不同以及我应该何时使用它们?

我见过以下触发器:

  • Trigger
  • DataTrigger
  • MultiTrigger
  • MultiDataTrigger
  • EventTrigger

What are the different triggers in WPF? How do they differ and when should I use them?

I've seen the following triggers:

  • Trigger
  • DataTrigger
  • MultiTrigger
  • MultiDataTrigger
  • EventTrigger

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

橙幽之幻 2024-08-28 04:50:43

触发器通常用在样式或控制模板中。它触发模板化事物的属性,并设置控件(或特定模板元素)的其他属性。例如,您可以在 IsMouseOver 上使用触发器来响应鼠标位于控件上方,并且设置器可能会更新画笔以显示“热”效果。

DataTrigger 在数据绑定上触发,而不是在控件属性上触发。它通常用在 DataTemplate 中。例如,如果 AlertLevel 属性等于 ZomgWereAllGoingToDie,则可以使用 DataTrigger 更改 DataTemplate 中元素的颜色。如果您想触发“转换”的控件属性(即在触发测试中使用 IValueConverter),DataTriggers 在控件模板中也很有用。例如,如果 Text 属性(被视为数字)为负数,则可以使用 DataTrigger 将 TextBox 的前景变成红色,方法是将 DataTrigger 与合适的 IValueConverter 以及 Self 或 TemplatedParent 的relativesource 结合使用。

MultiTrigger 和 MultiDataTrigger 是相同的,只不过它们允许您指定多个条件(分别是属性或绑定)并且仅在满足所有条件时才生效。

最后,EventTrigger 用于触发响应事件的操作(而不是更改一个状态以响应另一状态)。例如,您可以使用 EventTrigger 来响应 MouseEnter 事件。 EventTriggers 通常用于执行故事板,例如在事件发生时执行动画。

A Trigger is typically used in a Style or ControlTemplate. It triggers on properties of the thing being templated, and sets other properties of the control (or of specific template elements). For example, you would use a Trigger on IsMouseOver to respond to the mouse being over the control, and the setters might update a brush to show a "hot" effect.

A DataTrigger triggers on a data binding rather than on a control property. It is typically used in a DataTemplate. For example, you could use a DataTrigger to change the colour of an element in the DataTemplate if the AlertLevel property was equal to ZomgWereAllGoingToDie. DataTriggers can also be useful in control templates if you want to trigger on a "converted" control property (i.e. use an IValueConverter in the trigger test). For example, you could use a DataTrigger to turn a TextBox's Foreground red if the Text property, considered as a number, was negative, by using a DataTrigger with a suitable IValueConverter and a RelativeSource of Self or TemplatedParent.

MultiTrigger and MultiDataTrigger are the same, except they allow you to specify multiple conditions (properties or bindings respectively) and take effect only when all conditions are satisfied.

Finally, EventTrigger is used to trigger actions in response to events (as opposed to changing one piece of state in response to another piece of state). For example, you could use an EventTrigger to respond to the MouseEnter event. EventTriggers are typically used to execute storyboards, for example to perform an animation when the event occurs.

未央 2024-08-28 04:50:43

触发器通常用在StyleControlTemplate中。它触发正在模板化的任何内容的属性,并设置控件(或特定模板元素)的其他属性。例如,您可以在 IsMouseOver 上使用触发器来响应鼠标悬停在控件上,并且 setters 可能会更新画笔以显示“热”效果。

为什么使用触发器?

触发器在样式中使用,以便在属性值更改或事件触发时执行操作。触发器在控件上创建视觉效果。通过使用触发器,我们可以更改框架元素的外观。

WPF中有多少种类型的触发器?

WPF支持五种类型的触发器;它们是:

  1. 属性触发器
  2. 数据触发器
  3. MultiTrigger
  4. MultiDataTrigger
  5. 事件触发器

属性触发器

最简单的触发器形式是属性触发器;它监视依赖属性是否具有特定值。例如,如果我们想在用户将鼠标移到按钮上时以黄色点亮按钮,我们可以通过观察 IsMouseOver 属性的值为“ ”<代码>真”。

Property Trigger 当 UIElements 属性值更改时执行 Setter 集合。

要在任何控件上创建属性触发器,您必须以控件的样式设置触发器。

<Style x:Key="ButtonStyle" TargetType="{x:Type Button}">
    <Style.Triggers>
        <Trigger Property="IsPressed" Value="True">
            <Setter Property="Opacity" Value="0.5" />
        </Trigger>
        <Trigger Property="IsEnabled" Value="False">
            <Setter Property="Foreground" Value="Red" />
        </Trigger>
    </Style.Triggers>
</Style>

在上面的代码中,Trigger是在Button上创建的。当按钮的 IsPressed 属性更改时,它将把 Opacity 设置为 0.5。您可以在控件的任何依赖属性上设置触发器。
例如

 <Style x:Key="NormalStyle">
            <Setter Property="Control.FontSize" Value="20"></Setter>
            <Setter Property="Control.HorizontalAlignment" Value="Center"></Setter>
            <Setter Property="Control.Margin" Value="10"></Setter>
            <Setter Property="Control.Foreground" Value="Black"></Setter>
            <Style.Triggers>
                <Trigger Property="Control.IsMouseOver" Value="true">
                    <Setter Property="Control.FontStyle" Value="Italic"></Setter>
                    <Setter Property="Control.Foreground" Value="Red"></Setter>
                    <Setter Property="Control.Background" Value="Yellow"></Setter>
                </Trigger>
                <Trigger Property="Button.IsPressed" Value="true">
                    <Setter Property="Control.Foreground" Value="Green"></Setter>
                    <Setter Property="Control.Background" Value="Blue"></Setter>
                </Trigger>              
            </Style.Triggers>
        </Style>

MultiTrigger

MultiTrigger 用于设置多个属性更改时的操作。当 MulitTrigger.Condition 中的所有条件都满足时,它将执行。

<Style x:Key="MulitTriggerButtonStyle" TargetType="Button">
    <Style.Triggers>
        <MultiTrigger>
            <MultiTrigger.Conditions>
                <Condition Property="IsPressed" Value="True" />
                <Condition Property="Background" Value="BlanchedAlmond" />
            </MultiTrigger.Conditions>
            <MultiTrigger.Setters>
                <Setter Property="Foreground" Value="Blue" />
                <Setter Property="BorderThickness" Value="5" />
                <Setter Property="BorderBrush" Value="Blue" />
            </MultiTrigger.Setters>
        </MultiTrigger>
    </Style.Triggers>
</Style> 

事件触发器

事件触发器用于在FrameworkElement的RoatedEvent引发时执行操作。通常使用事件触发器在控件上执行一些动画(例如 colorAnimation、使用 KeyFrame 的 doubleAnumation 等)

我们先来了解一下StoryboardAnimation

动画:  

动画可以为用户界面提供更具吸引力的外观和感觉。我们还可以在控件上创建视觉效果,动画可以是任何类型,例如:

更改控件的背景颜色
 将屏幕旋转 90 度
 将对象从一个位置移动到另一个位置
 更改圆的不透明度(淡入/淡出)。

动画与 UIElement 的属性一起使用。 WPF 提供了与属性一起使用的不同类型的动画,例如:

颜色动画
用于在特定持续时间内对 UIElement 的颜色属性(SolidColorBrush、LinearGradientBrush)进行动画处理/更改。它有两个属性:

From(source) 和 To(target)

<Border Name="border1" Width="100" Height="30"
    BorderBrush="Black" BorderThickness="1">
    <Border.Background>
        <SolidColorBrush x:Name="MyBorder" Color="LightBlue" />
    </Border.Background>
    <Border.Triggers>
        <EventTrigger RoutedEvent="Mouse.MouseEnter">
            <BeginStoryboard>
               <Storyboard>
                <ColorAnimation Duration="0:0:1"
                    Storyboard.TargetName="MyBorder"
                    Storyboard.TargetProperty="Color" To="Gray" />
               </Storyboard>
            </BeginStoryboard>
        </EventTrigger>
    </Border.Triggers>
 </Border>

示例 2:

<TextBlock Visibility="Collapsed" Style="{StaticResource CDCStandardTextBlockStyle}" Name="TxtBlockTerminatingHeading" Text="{Binding NotifyOnTargetUpdated=True}" Foreground="Red" TextWrapping="Wrap" Margin="10,10,10,0">
 <TextBlock.Triggers>
                    <EventTrigger RoutedEvent="Binding.TargetUpdated">
                        <EventTrigger.Actions>
                            <BeginStoryboard>
                                <Storyboard BeginTime="00:00:00" RepeatBehavior="Forever" 
Storyboard.TargetName="TxtBlockTerminatingHeading" 
Storyboard.TargetProperty="(Foreground).(SolidColorBrush.Color)">
                                    <ColorAnimation From="Red" To="#f0f0f0" 
Duration="0:0:1"/>
                                </Storyboard>
                            </BeginStoryboard>
                        </EventTrigger.Actions>
                    </EventTrigger>
                </TextBlock.Triggers>
            </TextBlock>

示例 3:

<ListBox Name="employeeListBox" ItemsSource="{Binding 
empList}" Grid.Row="0" SelectedItem="{Binding SelectedIndex}">
      <i:Interaction.Triggers>
        <i:EventTrigger EventName="SelectionChanged">
          <i:InvokeCommandAction Command="{Binding MyCommand}" CommandParameter="{Binding 
ElementName=employeeListBox, Path=SelectedValue}"/>
        </i:EventTrigger>
      </i:Interaction.Triggers>
    </ListBox>

DataTrigger

DataTriggers 是监视绑定值而不是 Dependency 的触发器 属性。它们允许您观察绑定表达式,并在该绑定的计算结果等于您的值时做出反应。顾名思义,DataTrigger 应用属性值对绑定到 UIElement 的数据执行操作。
DataTrigger 允许在绑定数据匹配指定条件时设置属性值。例如:

<DataTemplate>
    <Grid Margin="0 5 0 0">
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto" />
            <RowDefinition Height="Auto" />
        </Grid.RowDefinitions>
        <Image x:Name="viewImage"
            Grid.Row="0" Width="100"             
            Height="60" HorizontalAlignment="Center"            
            Source="{Binding Picture}" Stretch="Fill" />            
        <TextBlock x:Name="viewText"
            Grid.Row="1" Margin="0 5 0 0"            
            HorizontalAlignment="Center"
            FontWeight="Black" Foreground="Green"            
            Text="{Binding Title}" />
    </Grid>
    <DataTemplate.Triggers>
       <DataTrigger Binding="{Binding Path=Picture}" Value="{x:Null}">
        <Setter TargetName="viewImage" Property="Source" Value="/Images/noImage.png" />
        <Setter TargetName="viewText" Property="Text" Value="No Image Available" />
        <Setter TargetName="viewText" Property="Foreground" Value="Red" />
       </DataTrigger>
    </DataTemplate.Triggers>
</DataTemplate>
<Style.Triggers>
                <DataTrigger Binding="{Binding ElementName=textBox1, Path=Text.Length}" 
Value="0">
                    <Setter Property="IsEnabled" Value="False"></Setter>
                </DataTrigger>
            </Style.Triggers>
        </Style>

MultiDataTrigger

MultiTriggerMultiDataTrigger 是相同的,只不过它们允许您指定多个条件(分别是属性或绑定)并且仅生效当所有条件都满足时。

<DataTemplate.Triggers>
    <MultiDataTrigger>
        <MultiDataTrigger.Conditions>
            <Condition Binding="{Binding Path=Picture}" Value="{x:Null}" />
            <Condition Binding="{Binding Path=Title}" Value="Waterfall" />
        </MultiDataTrigger.Conditions>
        <MultiDataTrigger.Setters>
           <Setter TargetName="viewImage" Property="Source" Value="/Images/noImage.png"/>
           <Setter TargetName="viewImage" Property="Opacity" Value="0.5" />
           <Setter TargetName="viewText" Property="Background" Value="Brown" />
        </MultiDataTrigger.Setters>
    </MultiDataTrigger>
</DataTemplate.Triggers>

A Trigger is typically used in a Style or ControlTemplate. It triggers on properties of whatever is being templated, and sets other properties of the control (or of specific template elements). For example, you would use a Trigger on IsMouseOver to respond to the mouse being over the control, and the setters might update a brush to show a "hot" effect.

Why use Triggers?

Triggers are used in styles to perform actions when a property value changes or when an event fires. Triggers create visual effects on controls. By using Triggers we can change the appearance of Framework Elements.

How many types of triggers are there in WPF?

There are five types of triggers supported by WPF; they are:

  1. Property Trigger
  2. Data Trigger
  3. MultiTrigger
  4. MultiDataTrigger
  5. Event Trigger

Property Trigger

The simplest form of a trigger is a property trigger; it watches for a dependency property to have a certain value. For example, if we wanted to light up a button in yellow as the user moves the mouse over it, we can do that by watching for the IsMouseOver property to have a value of "True".

Property Trigger Executes Collections of Setters, when UIElements property value changes.

To create a property trigger on any controls, you have to set trigger in style of the control.

<Style x:Key="ButtonStyle" TargetType="{x:Type Button}">
    <Style.Triggers>
        <Trigger Property="IsPressed" Value="True">
            <Setter Property="Opacity" Value="0.5" />
        </Trigger>
        <Trigger Property="IsEnabled" Value="False">
            <Setter Property="Foreground" Value="Red" />
        </Trigger>
    </Style.Triggers>
</Style>

In the above code, Trigger is created on Button. It will set Opacity to 0.5 when the button's IsPressed property changes. You can set a trigger on any Dependency Property of the control.
e.g.

 <Style x:Key="NormalStyle">
            <Setter Property="Control.FontSize" Value="20"></Setter>
            <Setter Property="Control.HorizontalAlignment" Value="Center"></Setter>
            <Setter Property="Control.Margin" Value="10"></Setter>
            <Setter Property="Control.Foreground" Value="Black"></Setter>
            <Style.Triggers>
                <Trigger Property="Control.IsMouseOver" Value="true">
                    <Setter Property="Control.FontStyle" Value="Italic"></Setter>
                    <Setter Property="Control.Foreground" Value="Red"></Setter>
                    <Setter Property="Control.Background" Value="Yellow"></Setter>
                </Trigger>
                <Trigger Property="Button.IsPressed" Value="true">
                    <Setter Property="Control.Foreground" Value="Green"></Setter>
                    <Setter Property="Control.Background" Value="Blue"></Setter>
                </Trigger>              
            </Style.Triggers>
        </Style>

MultiTrigger

MultiTrigger is used to set an action on Multiple Property change. It will execute when all conditions are satisfied within MulitTrigger.Condition.

<Style x:Key="MulitTriggerButtonStyle" TargetType="Button">
    <Style.Triggers>
        <MultiTrigger>
            <MultiTrigger.Conditions>
                <Condition Property="IsPressed" Value="True" />
                <Condition Property="Background" Value="BlanchedAlmond" />
            </MultiTrigger.Conditions>
            <MultiTrigger.Setters>
                <Setter Property="Foreground" Value="Blue" />
                <Setter Property="BorderThickness" Value="5" />
                <Setter Property="BorderBrush" Value="Blue" />
            </MultiTrigger.Setters>
        </MultiTrigger>
    </Style.Triggers>
</Style> 

Event Trigger

Event Trigger is used to perform an action when RoutedEvent of FrameworkElement is raised.Event Trigger is generally used to perform some animation on a control (like colorAnimation, doubleAnumation using KeyFrame, etc.)  

Let's first understand Storyboard and Animation.

Animations:  

An animation can provide user interface more attractive with look and feel. We can also create visual effects on the control, Animation can be any type like:

 change background color of the control
 rotate screen in 90 degree angle
 move object from one location to another
 Change Opacity (FadeIn/FadeOut) of the circle. 

Animation is used with Property of the UIElement. WPF provides different types of animation used with properties, like: 

ColorAnimation :
used to animate/change the color property (SolidColorBrush, LinearGradientBrush) of the UIElement over specific Duration. It has two properties :

From(source) and To(target)

<Border Name="border1" Width="100" Height="30"
    BorderBrush="Black" BorderThickness="1">
    <Border.Background>
        <SolidColorBrush x:Name="MyBorder" Color="LightBlue" />
    </Border.Background>
    <Border.Triggers>
        <EventTrigger RoutedEvent="Mouse.MouseEnter">
            <BeginStoryboard>
               <Storyboard>
                <ColorAnimation Duration="0:0:1"
                    Storyboard.TargetName="MyBorder"
                    Storyboard.TargetProperty="Color" To="Gray" />
               </Storyboard>
            </BeginStoryboard>
        </EventTrigger>
    </Border.Triggers>
 </Border>

Example 2:

<TextBlock Visibility="Collapsed" Style="{StaticResource CDCStandardTextBlockStyle}" Name="TxtBlockTerminatingHeading" Text="{Binding NotifyOnTargetUpdated=True}" Foreground="Red" TextWrapping="Wrap" Margin="10,10,10,0">
 <TextBlock.Triggers>
                    <EventTrigger RoutedEvent="Binding.TargetUpdated">
                        <EventTrigger.Actions>
                            <BeginStoryboard>
                                <Storyboard BeginTime="00:00:00" RepeatBehavior="Forever" 
Storyboard.TargetName="TxtBlockTerminatingHeading" 
Storyboard.TargetProperty="(Foreground).(SolidColorBrush.Color)">
                                    <ColorAnimation From="Red" To="#f0f0f0" 
Duration="0:0:1"/>
                                </Storyboard>
                            </BeginStoryboard>
                        </EventTrigger.Actions>
                    </EventTrigger>
                </TextBlock.Triggers>
            </TextBlock>

Example 3:

<ListBox Name="employeeListBox" ItemsSource="{Binding 
empList}" Grid.Row="0" SelectedItem="{Binding SelectedIndex}">
      <i:Interaction.Triggers>
        <i:EventTrigger EventName="SelectionChanged">
          <i:InvokeCommandAction Command="{Binding MyCommand}" CommandParameter="{Binding 
ElementName=employeeListBox, Path=SelectedValue}"/>
        </i:EventTrigger>
      </i:Interaction.Triggers>
    </ListBox>

DataTrigger

DataTriggers are Triggers that watch a bound value instead of a Dependency Property. They allow you to watch a bound expression, and will react when that binding evaluates equal to your value. As the name suggests, DataTrigger applies property value to perform action on Data that Binding to the UIElement.
DataTrigger allows to set property value when Binding Data matches specified condition. For example:

<DataTemplate>
    <Grid Margin="0 5 0 0">
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto" />
            <RowDefinition Height="Auto" />
        </Grid.RowDefinitions>
        <Image x:Name="viewImage"
            Grid.Row="0" Width="100"             
            Height="60" HorizontalAlignment="Center"            
            Source="{Binding Picture}" Stretch="Fill" />            
        <TextBlock x:Name="viewText"
            Grid.Row="1" Margin="0 5 0 0"            
            HorizontalAlignment="Center"
            FontWeight="Black" Foreground="Green"            
            Text="{Binding Title}" />
    </Grid>
    <DataTemplate.Triggers>
       <DataTrigger Binding="{Binding Path=Picture}" Value="{x:Null}">
        <Setter TargetName="viewImage" Property="Source" Value="/Images/noImage.png" />
        <Setter TargetName="viewText" Property="Text" Value="No Image Available" />
        <Setter TargetName="viewText" Property="Foreground" Value="Red" />
       </DataTrigger>
    </DataTemplate.Triggers>
</DataTemplate>
<Style.Triggers>
                <DataTrigger Binding="{Binding ElementName=textBox1, Path=Text.Length}" 
Value="0">
                    <Setter Property="IsEnabled" Value="False"></Setter>
                </DataTrigger>
            </Style.Triggers>
        </Style>

MultiDataTrigger

MultiTrigger and MultiDataTrigger are the same, except they allow you to specify multiple conditions (properties or bindings respectively) and take effect only when all conditions are satisfied.

<DataTemplate.Triggers>
    <MultiDataTrigger>
        <MultiDataTrigger.Conditions>
            <Condition Binding="{Binding Path=Picture}" Value="{x:Null}" />
            <Condition Binding="{Binding Path=Title}" Value="Waterfall" />
        </MultiDataTrigger.Conditions>
        <MultiDataTrigger.Setters>
           <Setter TargetName="viewImage" Property="Source" Value="/Images/noImage.png"/>
           <Setter TargetName="viewImage" Property="Opacity" Value="0.5" />
           <Setter TargetName="viewText" Property="Background" Value="Brown" />
        </MultiDataTrigger.Setters>
    </MultiDataTrigger>
</DataTemplate.Triggers>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文