触发器是指当满足预设的条件时去执行一些事务的工具,比如我们希望鼠标移到某个按钮上方时,这个按钮的颜色、大小发生一些改变。这个时候,条件是鼠标移到按钮上,执行的事务是改变按钮的颜色和大小。
触发器种类
触发器主要运用的场景在Style、ControlTemplate、DataTemplate三个地方。
style中
<Window.Resources><Style x:Key="GreenButtonStyle" TargetType="Button"><Setter Property="Width" Value="100"/><Setter Property="Height" Value="30"/><Setter Property="Background" Value="Green"/><Setter Property="Foreground" Value="White"/><Setter Property="Margin" Value="3"/><Style.Triggers><Trigger Property="IsMouseOver" Value="True"><Setter Property="Foreground" Value="Red"/><Setter Property="Width" Value="150"/><Setter Property="Height" Value="50"/><Setter Property="Content" Value="鼠标移入"/></Trigger> </Style.Triggers></Style></Window.Resources><StackPanel VerticalAlignment="Center"><Button Content="按钮" Style="{StaticResource GreenButtonStyle}"/></StackPanel>
这种情况下改变不了background的值的。要想改变background,需要利用模版重写
ControlTemplate中
实例如下:
步骤1:创建用户字典ButtonStyle.xaml,放在Style文件夹下
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"><Style TargetType="Button" x:Key="ButtonTemplate" ><Setter Property="Width" Value="100"></Setter><Setter Property="Height" Value="30"></Setter><Setter Property="Background" Value="Blue"></Setter><Setter Property="Foreground" Value="White"></Setter><Setter Property="Template"><Setter.Value><ControlTemplate TargetType="Button"><Border Background="{TemplateBinding Background}"><ContentPresenter HorizontalAlignment="Center"VerticalAlignment="Center"></ContentPresenter></Border><ControlTemplate.Triggers><Trigger Property="IsMouseOver" Value="True"><Setter Property="Background" Value="#409eff"/></Trigger></ControlTemplate.Triggers></ControlTemplate></Setter.Value></Setter></Style></ResourceDictionary>
步骤2:在app.xaml中引入,全局可用
<Application.Resources><ResourceDictionary><ResourceDictionary.MergedDictionaries><ResourceDictionary Source="Style/ButtonStyle.xaml"></ResourceDictionary></ResourceDictionary.MergedDictionaries></ResourceDictionary></Application.Resources>
步骤3:在任意view中使用
<Button Content="模版按钮" Style="{StaticResource ButtonTemplate }"></Button>
结果如下:
Background="{TemplateBinding Background}"实现了将Background绑定,ControlTemplate 重写了Button。