属性触发器
<Style TargetType="ListBoxItem">
<Setter Property="Opacity" Value="0.5" />
<Setter Property="MaxHeight" Value="75" />
<Style.Triggers>
<Trigger Property="IsSelected" Value="True">
<Trigger.Setters>
<Setter Property="Opacity" Value="1.0" />
</Trigger.Setters>
</Trigger>
</Style.Triggers>
</Style>
表示 ListBoxItem的isselected属性值为true 时,其Opacity值为1
数据触发器
使用 DataTrigger,可以在数据对象的属性值与指定的 Value 匹配时设置属性值。例如,在显示 Employee 对象列表时,可能希望前景色根据每个 Employee 的当前出勤情况而变化。(例如,用紫色前景色显示当前正在休假的 Employee。)
查看代码片段3
<Window.Resources> <c:Places x:Key="PlacesData"/> <Style TargetType="ListBoxItem"> <Style.Triggers> <DataTrigger Binding="{Binding Path=State}" Value="WA"> <Setter Property="Foreground" Value="Red" /> </DataTrigger> <MultiDataTrigger> <MultiDataTrigger.Conditions> <Condition Binding="{Binding Path=Name}" Value="Portland" /> <Condition Binding="{Binding Path=State}" Value="OR" /> </MultiDataTrigger.Conditions> <Setter Property="Background" Value="Cyan" /> </MultiDataTrigger> </Style.Triggers> </Style> <DataTemplate DataType="{x:Type c:Place}"> <Canvas Width="160" Height="20"> <TextBlock FontSize="12" Width="130" Canvas.Left="0" Text="{Binding Path=Name}"/> <TextBlock FontSize="12" Width="30" Canvas.Left="130" Text="{Binding Path=State}"/> </Canvas> </DataTemplate> </Window.Resources> <StackPanel> <TextBlock FontSize="18" Margin="5" FontWeight="Bold" HorizontalAlignment="Center">Data Trigger Sample</TextBlock> <ListBox Width="180" HorizontalAlignment="Center" Background="Honeydew" ItemsSource="{Binding Source={StaticResource PlacesData}}"/> </StackPanel>
1.单条件触发 以上的DataTrigger就是一个单条件触发器。
2. 多条件触发器 以上的MultiDataTrigger就是一个多条件触发器。
事件触发器
属性触发器用来检查从属属性的值,数据触发器用来检查CLR属性的值,而事件触发器用来监视事件。当一个事件发生的时候,事件触发器就会通过引发相关的动画事件来响应。
如代码片段4:
如代码片段4:
<Style TargetType="ListBoxItem"> <Setter Property="Opacity" Value="0.5" /> <Setter Property="MaxHeight" Value="75" /> <Style.Triggers> <Trigger Property="IsSelected" Value="True"> <Trigger.Setters> <Setter Property="Opacity" Value="1.0" /> </Trigger.Setters> </Trigger> <EventTrigger RoutedEvent="Mouse.MouseEnter"> <EventTrigger.Actions> <BeginStoryboard> <Storyboard> <DoubleAnimation Duration="0:0:0.2" Storyboard.TargetProperty="MaxHeight" To="90" /> </Storyboard> </BeginStoryboard> </EventTrigger.Actions> </EventTrigger> <EventTrigger RoutedEvent="Mouse.MouseLeave"> <EventTrigger.Actions> <BeginStoryboard> <Storyboard> <DoubleAnimation Duration="0:0:1" Storyboard.TargetProperty="MaxHeight" /> </Storyboard> </BeginStoryboard> </EventTrigger.Actions> </EventTrigger> </Style.Triggers> </Style>