简谈WPF触发器(Trigger)

简谈WPF触发器(Trigger)

什么是触发器?

提供给程序员的一种执行任务事件的方法.当满足某个条件触发执行.简而言之便是:根据不同的条件来执行特定的任务.

比如,自动更改外观属性,执行UI动画等等.

而在在WPF中有三种类型的触发器:

  • 属性触发器Property Trigger
  • 数据触发器Data Trigger
  • 事件触发器Event Trigger

属性触发器Property Trigger

在WPF中最为常用的便是它了.属性触发器,顾名思义.当属性的值发生变化将会引发触发器.

举一个简单的例子(鼠标移动到上面颜色变为红色):

1
2
3
4
5
6
7
8
9
10
11
<TextBlock Text="TEST" Width="140" Height="45">
<TextBlock.Style>
<Style TargetType="TextBlock">
<Style.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="Foreground" Value="Red" />
</Trigger>
</Style.Triggers>
</Style>
</TextBlock.Style>
</TextBlock>

相信在看过如上的例子,各位已经知晓其作用.不过….仅仅能更换颜色?不这还不够…..

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
<Style x:Key="btnLink_forum" TargetType="Button">
<Setter Property="Background">
<Setter.Value>
<ImageBrush ImageSource="/HYUN;component/picRes/btnLink_Normal.png">
</ImageBrush>
</Setter.Value>
</Setter>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type Button}">
<Border Background="{TemplateBinding Background}" BorderThickness="0">
<ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center"/>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
<Style.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="Background">
<Setter.Value>
<ImageBrush ImageSource="/HYUN;component/picRes/btnLink_Hover.png"/>
</Setter.Value>
</Setter>
</Trigger>
<Trigger Property="IsPressed" Value="True">
<Setter Property="Background">
<Setter.Value>
<ImageBrush ImageSource="/HYUN;component/picRes/btnLink_Push.png"/>
</Setter.Value>
</Setter>
</Trigger>
</Style.Triggers>
</Style>

如上,在鼠标划过按钮分别提供三种不同的样式.

待更新….

# c#, wpf

评论

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×