构成Style最重要的两种元素是Setter和Trigger
Setter类帮助我们设置控件的静态外观风格
Trigger类帮助我们设置控件的行为风格
Setter类的Property属性是用来指明你想为目标的哪个属性赋值;Value属性则是你提供的属性值:例如在Window的资源词典中放置一个针对TextBlock的Style,Style中使用若干 Setter来设定TextBlock的一些属性,这样程序中的TextBlock就会具有统一的风格,除非使用{x:Null}显示地清空Style.
Trigger类最基本的是触发器,Property是Trigger关键的属性名称,Value是触发条件,Trigger类还有一个Setters属性,此属性是一组Setter,一旦触发条件被满足,这组Setter 的“属性-值”就会被应用,触发条件不再满足后,各属性值会被还原。
Style中的Setter
<Window x:Class="Style中的Setter.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 TargetType="TextBlock"> <Style.Setters> <Setter Property="FontSize" Value="24"/> <Setter Property="TextDecorations" Value="Underline"/> <Setter Property="FontStyle" Value="Italic"/> </Style.Setters> </Style> </Window.Resources> <StackPanel Margin="5"> <TextBlock Text="Hello Wpf"/> <TextBlock Text="This is a sample"/> <TextBlock Text="by time 2009" Style="{x:Null}"></TextBlock> </StackPanel> </Window>
Style中的Trigger
<Window x:Class="Style中的Trigger.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 TargetType="CheckBox" x:Key="myStyle"> <Style.Triggers> <Trigger Property="IsChecked" Value="True"> <Setter Property="FontSize" Value="20"/> <Setter Property="Foreground" Value="Orange"/> </Trigger> </Style.Triggers> </Style> </Window.Resources> <StackPanel> <CheckBox Content="悄悄地我走了" Margin="5" Style="{StaticResource myStyle}"/> <CheckBox Content="正如我轻轻的来" Margin="5"/> <CheckBox Content="我挥一挥衣袖" Margin="5"/> <CheckBox Content="不带走一片云彩" Margin="5"/> </StackPanel> </Window>
如果想全部应用的话那就去掉x:Key="myStyle"
原文:http://www.cnblogs.com/chenyongblog/p/3573949.html