wpf中的触发器是应用于程序界面模板、样式、皮肤、主题的基础。以下作为学习的记录。
1,三种基本触发器,属性触发器、数据触发器、事件触发器
属性触发器
1 <!--属性触发器--> 2 <TextBox TextWrapping="Wrap" Margin="5"> 3 <TextBox.Style> 4 <Style TargetType="TextBox"> 5 <Style.Triggers> 6 <Trigger Property="Text" Value="text"> 7 <Setter Property="Background" Value="Aqua"></Setter> 8 </Trigger> 9 </Style.Triggers> 10 </Style> 11 </TextBox.Style> 12 </TextBox>
数据触发器
1 <!--数据触发器--> 2 <TextBox TextWrapping="Wrap" Margin="5"> 3 <TextBox.Style> 4 <Style TargetType="TextBox"> 5 <Style.Triggers> 6 <DataTrigger Binding="{Binding RelativeSource={RelativeSource Mode=Self},Path=Text}" Value="text"> 7 <Setter Property="Background" Value="Red"></Setter> 8 </DataTrigger> 9 </Style.Triggers> 10 </Style> 11 </TextBox.Style> 12 </TextBox>
事件触发器
1 <!--事件触发器--> 2 <Window.Resources> 3 <PathGeometry x:Key="ellipse"> 4 <PathFigure IsClosed="True" StartPoint="0,50"> 5 <ArcSegment Size="50,000" Point="100,50" SweepDirection="Clockwise"></ArcSegment> 6 </PathFigure> 7 </PathGeometry> 8 </Window.Resources> 9 <Canvas> 10 <Rectangle Name="rect" Canvas.Top="0" Canvas.Left="30" Height="30" Fill="Red"></Rectangle> 11 </Canvas> 12 <Window.Triggers> 13 <EventTrigger RoutedEvent="Window.Loaded"> 14 <BeginStoryboard> 15 <Storyboard BeginTime="0:0:0" RepeatBehavior="Forever"> 16 <DoubleAnimationUsingPath Storyboard.TargetName="rect" 17 Storyboard.TargetProperty="Width" 18 PathGeometry="{StaticResource ResourceKey=ellipse}" 19 Source="X" Duration="0:0:10"></DoubleAnimationUsingPath> 20 </Storyboard> 21 </BeginStoryboard> 22 </EventTrigger> 23 </Window.Triggers>
2,两种逻辑触发器,与逻辑触发器、或逻辑触发器
与逻辑触发器
1 <!--或逻辑触发器--> 2 <Button Content="press me" Width="150" Height="60"> 3 <Button.Style> 4 <Style TargetType="{x:Type Button}"> 5 <Style.Triggers> 6 <Trigger Property="Button.IsMouseOver" Value="True"> 7 <Setter Property="Button.Foreground" Value="Blue"></Setter> 8 </Trigger> 9 <Trigger Property="Button.IsPressed" Value="True"> 10 <Setter Property="Button.Foreground" Value="Red"></Setter> 11 </Trigger> 12 </Style.Triggers> 13 </Style> 14 </Button.Style> 15 </Button>
或逻辑触发器
1 <!--与逻辑触发器--> 2 <TextBox TextWrapping="Wrap" Margin="5"> 3 <TextBox.Style> 4 <Style TargetType="TextBox"> 5 <Style.Triggers> 6 <MultiTrigger> 7 <MultiTrigger.Conditions> 8 <Condition Property="Text" Value="text"></Condition> 9 <Condition Property="IsMouseOver" Value="True"></Condition> 10 </MultiTrigger.Conditions> 11 <Setter Property="Foreground" Value="Aqua"></Setter> 12 </MultiTrigger> 13 </Style.Triggers> 14 </Style> 15 </TextBox.Style> 16 </TextBox>