c#:WPF初级触发器的使用 Triggers
触发器可以动态改变控件的外观
代码使用:
单条件触发器
<Style x:Key="defaultstyle" TargetType="Button">
<Setter Property="FontSize" Value="40" ></Setter>
<Setter Property="Background" Value="Pink"></Setter>
<Style.Triggers>
<Trigger Property="IsMouseOver" Value="True">//事件触发器
<Setter Property="Foreground" Value="Black"></Setter>
</Trigger>
<Trigger Property="IsMouseDirectlyOver" Value="True">//事件触发器
<Setter Property="FontSize" Value="33"></Setter>
</Trigger>
</Style.Triggers>
</Style>
多条件触发器
如果因为两个或多个属性同时改变时激活触发器,就可以使用MultiTrigger
Style.Triggers中加入
<Style.Triggers>
<MultiTrigger>
<MultiTrigger.Conditions>
<Condition Property="IsMouseOver" Value="True"/>
<Condition Property="IsFocused" Value="True"/>
</MultiTrigger.Conditions>
<MultiTrigger.Setters>
<Setter Property="Foreground" Value="Red"></Setter>
</MultiTrigger.Setters>
</MultiTrigger>
</Style.Triggers>
事件触发器
属性触发器在属性改变其值时激活,事件触发器在事件发生时激活。控件存在的事件都有对应的事件触发器。
<Window.Resources>
<Style x:Key="defaultstyle" TargetType="Button">
<Setter Property="FontSize" Value="40" ></Setter>
<Setter Property="Background" Value="Pink"></Setter>
<Style.Triggers>
<EventTrigger RoutedEvent="MouseEnter">
<EventTrigger.Actions>
<BeginStoryboard>
<Storyboard FillBehavior="Stop">
<ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Background">
<DiscreteObjectKeyFrame KeyTime="0:0:0.2">
<DiscreteObjectKeyFrame.Value>
<SolidColorBrush Color="Yellow" />
</DiscreteObjectKeyFrame.Value>
</DiscreteObjectKeyFrame>
</ObjectAnimationUsingKeyFrames>
</Storyboard>
</BeginStoryboard>
</EventTrigger.Actions>
</EventTrigger>
</Style.Triggers>
</Style>
</Window.Resources>