[WPF系列]-基础系列 Trigger, DataTrigger & EventTrigger

So far, we worked with styles by setting a static value for a specific property. However, using triggers, you can change the value of a given property, once a certain condition changes. Triggers come in multiple flavors: Property triggers, event triggers and data triggers. They allow you to do stuff that would normally be done in code-behind completely in markup instead, which is all a part of the ongoing process of separating style and code.

Property trigger

The most common trigger is the property trigger, which in markup is simply defined with a <Trigger> element. It watches a specific property on the owner control and when that property has a value that matches the specified value, properties can change. In theory this might sound a bit complicated, but it‘s actually quite simple once we turn theory into an example:

Download sample

<Window x:Class="WpfTutorialSamples.Styles.StyleTriggersSample"        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"        Title="StyleTriggersSample" Height="100" Width="300">    <Grid>        <TextBlock Text="Hello, styled world!" FontSize="28" HorizontalAlignment="Center" VerticalAlignment="Center">            <TextBlock.Style>                <Style TargetType="TextBlock">                    <Setter Property="Foreground" Value="Blue"></Setter>                    <Style.Triggers>                        <Trigger Property="IsMouseOver" Value="True">                            <Setter Property="Foreground" Value="Red" />                            <Setter Property="TextDecorations" Value="Underline" />                        </Trigger>                    </Style.Triggers>                </Style>            </TextBlock.Style>        </TextBlock>    </Grid></Window>

In this style, we set the Foreground property to blue, to make it look like a hyperlink. We then add a trigger, which listens to theIsMouseOver property - once this property changes to True, we apply two setters: We change the Foreground to red and then we make it underlined. This is a great example on how easy it is to use triggers to apply design changes, completely without any code-behind code.

We define a local style for this specific TextBlock, but as shown in the previous articles, the style could have been globally defined as well, if we wanted it to apply to all TextBlock controls in the application.

Data triggers

Data triggers, represented by the <DataTrigger> element, are used for properties that are not necessarily dependency properties. They work by creating a binding to a regular property, which is then monitored for changes. This also opens up for binding your trigger to a property on a different control. For instance, consider the following example:

Download sample

<Window x:Class="WpfTutorialSamples.Styles.StyleDataTriggerSample"        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"        Title="StyleDataTriggerSample" Height="200" Width="200">    <StackPanel HorizontalAlignment="Center" VerticalAlignment="Center">        <CheckBox Name="cbSample" Content="Hello, world?" />        <TextBlock HorizontalAlignment="Center" Margin="0,20,0,0" FontSize="48">            <TextBlock.Style>                <Style TargetType="TextBlock">                    <Setter Property="Text" Value="No" />                    <Setter Property="Foreground" Value="Red" />                    <Style.Triggers>                        <DataTrigger Binding="{Binding ElementName=cbSample, Path=IsChecked}" Value="True">                            <Setter Property="Text" Value="Yes!" />                            <Setter Property="Foreground" Value="Green" />                        </DataTrigger>                    </Style.Triggers>                </Style>            </TextBlock.Style>        </TextBlock>    </StackPanel></Window>

In this example, we have a CheckBox and a TextBlock. Using a DataTrigger, we bind the TextBlock to the IsCheckedproperty of the CheckBox. We then supply a default style, where the text is "No" and the foreground color is red, and then, using a DataTrigger, we supply a style for when the IsChecked property of the CheckBox is changed to True, in which case we make it green with a text saying "Yes!" (as seen on the screenshot).

 

Event triggers

Event triggers, represented by the <EventTrigger> element, are mostly used to trigger an animation, in response to an event being called. We haven‘t discussed animations yet, but to demonstrate how an event trigger works, we‘ll use them anyway. Have a look on the chapter about animations for more details. Here‘s the example:

Download sample

<Window x:Class="WpfTutorialSamples.Styles.StyleEventTriggerSample"        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"        Title="StyleEventTriggerSample" Height="100" Width="300">    <Grid>        <TextBlock Name="lblStyled" Text="Hello, styled world!" FontSize="18" HorizontalAlignment="Center" VerticalAlignment="Center">            <TextBlock.Style>                <Style TargetType="TextBlock">                    <Style.Triggers>                        <EventTrigger RoutedEvent="MouseEnter">                            <EventTrigger.Actions>                                <BeginStoryboard>                                    <Storyboard>                                        <DoubleAnimation Duration="0:0:0.300" Storyboard.TargetProperty="FontSize" To="28" />                                    </Storyboard>                                </BeginStoryboard>                            </EventTrigger.Actions>                        </EventTrigger>                        <EventTrigger RoutedEvent="MouseLeave">                            <EventTrigger.Actions>                                <BeginStoryboard>                                    <Storyboard>                                        <DoubleAnimation Duration="0:0:0.800" Storyboard.TargetProperty="FontSize" To="18" />                                    </Storyboard>                                </BeginStoryboard>                            </EventTrigger.Actions>                        </EventTrigger>                    </Style.Triggers>                </Style>            </TextBlock.Style>        </TextBlock>    </Grid></Window>

The markup might look a bit overwhelming, but if you run this sample and look at the result, you‘ll see that we‘ve actually accomplished a pretty cool animation, going both ways, in ~20 lines of XAML. As you can see, I use an EventTrigger to subscribe to two events: MouseEnter and MouseLeave. When the mouse enters, I make a smooth and animated transition to a FontSize of 28 pixels in 300 milliseconds. When the mouse leaves, I change the FontSize back to 18 pixels but I do it a bit slower, just because it looks kind of cool.

Summary

WPF styles make it easy to get a consistent look, and with triggers, this look becomes dynamic. Styles are great in your application, but they‘re even better when used in control templates etc. You can read more about that elsewhere in this tutorial.

In the next article, we‘ll look at multi triggers, which allow us to apply styles based on multiple properties.

 

引用自 Trigger, DataTrigger & EventTrigger

时间: 2024-10-12 15:23:01

[WPF系列]-基础系列 Trigger, DataTrigger & EventTrigger的相关文章

[转载]WPF入门教程系列一——基础

一. 前言   最近在学习WPF,学习WPF首先上的是微软的MSDN,然后再搜索了一下网络有关WPF的学习资料.为了温故而知新把学习过程记录下来,以备后查.这篇主要讲WPF的开发基础,介绍了如何使用Visual Studio 2013创建一个WPF应用程序. 首先说一下学习WPF的基础知识: 1) 要会一门.NET所支持的编程语言.例如C#. 2) 会一点“标准通用标记语言”:WPF窗体程序使用的XAML语言,也属于“标准通用标记语言”的一个分支.如果以前接触过XML.HTML.XHTML.AS

WPF入门教程系列一——基础

一. 前言   最近在学习WPF,学习WPF首先上的是微软的MSDN,然后再搜索了一下网络有关WPF的学习资料.为了温故而知新把学习过程记录下来,以备后查.这篇主要讲WPF的开发基础,介绍了如何使用Visual Studio 2013创建一个WPF应用程序. 首先说一下学习WPF的基础知识: 1) 要会一门.NET所支持的编程语言.例如C#. 2) 会一点"标准通用标记语言":WPF窗体程序使用的XAML语言,也属于"标准通用标记语言"的一个分支.如果以前接触过XM

WPF入门教程系列(一) 创建你的第一个WPF项目

WPF入门教程系列(一) 创建你的第一个WPF项目 WPF基础知识 快速学习绝不是从零学起的,良好的基础是快速入手的关键,下面先为大家摞列以下自己总结的学习WPF的几点基础知识: 1) C#基础语法知识(或者其他.NET支持的语言):这个是当然的了,虽然WPF是XAML配置的,但是总还是要写代码的,相信各位读者应该也都有这个基础了. 2) HTML语言:虽然WPF是窗体程序但是由于使用的XAML语言,如果以前接触过HTML.XHTML.ASP.NET之路的东西的话会,接受这些标签会很有帮助的,如

WPF入门教程系列(二) 深入剖析WPF Binding的使用方法

WPF入门教程系列(二) 深入剖析WPF Binding的使用方法 同一个对象(特指System.Windows.DependencyObject的子类)的同一种属性(特指DependencyProperty)只能拥有一个binding. 这一点可以通过设置binding对象的方法名得知: public static BindingExpressionBase SetBinding( DependencyObject target, DependencyProperty dp, BindingB

WPF入门教程系列二——Application介绍

原文:WPF入门教程系列二--Application介绍 一.Application介绍 WPF和WinForm 很相似, WPF与WinForm一样有一个 Application对象来进行一些全局的行为和操作,并且每个 Domain (应用程序域)中仅且只有一个 Application 实例存在.和 WinForm 不同的是WPF Application默认由两部分组成 : App.xaml 和 App.xaml.cs,这有点类似于 Asp.Net WebForm,将定义和行为代码相分离. 微

WPF编游戏系列 之六 动画效果(1)

原文:WPF编游戏系列 之六 动画效果(1)        本篇主要针对界面进行动画效果处理.首先在打开或关闭界面时,使其产生动态效果而不是生硬的显示或消失(如下图).其次在鼠标放到关闭窗口图标上时,使其出现闪动效果.下面将通过Storyboard和EventTrigger实现这些效果.     1. 先从简单的入手吧,为关闭图标增加闪动效果,首先要在ScrollViewer中添加一个关闭窗口图标. ... ... <ScrollViewer Name="queryScrollViewer

DOM系列---基础篇

DOM (Document Object Model) 即文档对象模型, 针对 HTML 和 XML 文档的 API (应用程序接口) .DOM 描绘了一个层次化的节点树,运行开发人员添加.移除和修改页面的某一部分.DOM 产生于 网景公司及微软公司创始的 DHTML(动态 HTML) ,但现在它已经成为表现和操作页面标记的真正跨平台.语言中立的方式. DOM 中的三个字母: D(文档)可以理解为整个 Web 加载的网页文档: O(对象)可以理解为类似 window 对象之类的东西,可以调用属性

C#基础系列:实现自己的ORM(反射以及Attribute在ORM中的应用)

反射以及Attribute在ORM中的应用 一. 反射什么是反射?简单点吧,反射就是在运行时动态获取对象信息的方法,比如运行时知道对象有哪些属性,方法,委托等等等等.反射有什么用呢?反射不但让你在运行是获取对象的信息,还提供运行时动态调用对象方法以及动态设置.获取属性等的能力.反射在ORM中有什么用呢?我这里所讨论的ORM实现是通过自定义Attribute的方式进行映射规则的描述的.但是我们并不知道具体哪个对象需要对应哪个表,并且这些对象是独立于我们的ORM框架的,所以我们只能通过自定义Attr

SQL Server调优系列基础篇(联合运算符总结)

前言 上两篇文章我们介绍了查看查询计划的方式,以及一些常用的连接运算符的优化技巧,本篇我们总结联合运算符的使用方式和优化技巧. 废话少说,直接进入本篇的主题. 技术准备 基于SQL Server2008R2版本,利用微软的一个更简洁的案例库(Northwind)进行解析. 一.联合运算符 所谓的联合运算符,其实应用最多的就两种:UNION ALL和UNION. 这两个运算符用法很简单,前者是将两个数据集结果合并,后者则是合并后进行去重操作,如果有过写T-SQL语句的码农都不会陌生. 我们来分析下