基本样式类似于CSS,用法也基本差不多,功能很强大,但更强大的是样式中的触发器,可根据某个特定的条件来触发样式的改变。
在应用中根据不同的特性可选择性的使用不同触发方式,总体归类为:
属性触发器
监视某个依赖项属性值,当值变化为正在等待的属性值时就会触发Trigger.Setters中的设置器。
<Window x:Class="MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="MainWindow" Height="350" Width="525"> <Window.Resources> <Style x:Key="style1"> <Style.Setters> <Setter Property="TextBox.Margin" Value="5"></Setter> </Style.Setters> <Style.Triggers> <Trigger Property="TextBox.Text" Value="我变"> <Setter Property="TextBox.Foreground" Value="Red"></Setter> </Trigger> </Style.Triggers> </Style> </Window.Resources> <StackPanel> <TextBox Text="哎哟" Style="{StaticResource style1}"></TextBox> </StackPanel> </Window>
键名为style1的样式,定义了一个简单的触发器,当应用该样式的TextBox.Text属性为“我变”时将前景色改变为红色。
数据绑定触发器
还没学,不会
事件触发器
普通触发器等待属性发生变化,而事件触发器则等待特定的事件被引发,比如鼠标相关事件等。
<Window x:Class="MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="MainWindow" Height="350" Width="525"> <Window.Resources> <Style x:Key="style1"> <Style.Triggers> <!--定义样式触发器--> <EventTrigger RoutedEvent="Mouse.MouseEnter"><!--事件触发器MouseEnter--> <EventTrigger.Actions><!--事件触发器必须的动作--> <BeginStoryboard><!--开始动画版--> <Storyboard><!--动画版的定义--> <DoubleAnimation Duration="0:0:0.5" Storyboard.TargetProperty="FontSize" To="22"></DoubleAnimation><!--双精度浮点型的时间线动作,周期为0.5秒,目标属性为字体大小,属性值在5秒内更改为22--> </Storyboard> </BeginStoryboard> </EventTrigger.Actions> </EventTrigger> </Style.Triggers> </Style> </Window.Resources> <Grid HorizontalAlignment="Center" VerticalAlignment="Center"> <TextBlock Style="{StaticResource style1}">事件触发器</TextBlock> </Grid> </Window>