WPF中的样式
在WPF中, Style定义给定可视元素的一个或多个依赖项属性的值。整个应用程序使用样式以使用户界面更加一致(例如,为所有对话框按钮提供一致的大小),并使批量更改更容易(例如,更改所有按钮的宽度。)
样式通常在应用程序中的高级ResourceDictionary中定义(例如在App.xaml或主题中),因此它可以在应用程序范围内使用,但也可以为单个元素及其子元素定义,例如应用样式到StackPanel内的所有TextBlock元素。
<StackPanel> <StackPanel.Resources> <Style TargetType="TextBlock"> <Setter Property="Margin" Value="5,5,5,0"/> <Setter Property="Background" Value="#FFF0F0F0"/> <Setter Property="Padding" Value="5"/> </Style> </StackPanel.Resources> <TextBlock Text="First Child"/> <TextBlock Text="Second Child"/> <TextBlock Text="Third Child"/> </StackPanel>
笔记
定义样式的位置会影响它的可用位置。
StaticResource无法解析转发引用。换句话说,如果你要定义依赖于资源字典中的另一个样式或资源的样式,则必须在它所依赖的资源之后/之下定义它。
StaticResource是引用样式和其他资源(出于性能和行为原因)的推荐方法,除非你特别要求使用DynamicResource ,例如,对于可在运行时更改的主题。
资源
MSDN上有关于样式和资源的详尽文章:
定义命名样式
命名样式需要设置x:Key属性,并且仅适用于按名称显式引用它的元素:
<StackPanel> <StackPanel.Resources> <Style x:Key="MyTextBlockStyle" TargetType="TextBlock"> <Setter Property="Background" Value="Yellow"/> <Setter Property="FontWeight" Value="Bold"/> </Style> </StackPanel.Resources> <TextBlock Text="Yellow and bold!" Style="{StaticResource MyTextBlockStyle}" /> <TextBlock Text="Also yellow and bold!" Style="{DynamicResource MyTextBlockStyle}" /> <TextBlock Text="Plain text." /> </StackPanel>
定义隐式样式
隐式样式适用于范围内给定类型的所有元素。隐式样式可以省略x:Key因为它与样式的TargetType属性隐式相同。
<StackPanel> <StackPanel.Resources> <Style TargetType="TextBlock"> <Setter Property="Background" Value="Yellow"/> <Setter Property="FontWeight" Value="Bold"/> </Style> </StackPanel.Resources> <TextBlock Text="Yellow and bold!" /> <TextBlock Text="Also yellow and bold!" /> <TextBlock Style="{x:Null}" Text="I'm not yellow or bold; I'm the control's default style!" /> </StackPanel>
继承风格
通常需要一种基本样式来定义属于同一控件的多个样式之间共享的属性/值,尤其是对于像TextBlock这样的东西。这是通过使用BasedOn属性完成的。值是继承的,然后可以被覆盖。
<Style x:Key="BaseTextBlockStyle" TargetType="TextBlock"> <Setter Property="FontSize" Value="12"/> <Setter Property="Foreground" Value="#FFBBBBBB" /> <Setter Property="FontFamily" Value="Arial" /> </Style> <Style x:Key="WarningTextBlockStyle" TargetType="TextBlock" BasedOn="{StaticResource BaseTextBlockStyle"> <Setter Property="Foreground" Value="Red"/> <Setter Property="FontWeight" Value="Bold" /> </Style>
在上面的示例中,使用样式WarningTextBlockStyle任何TextBlock将以红色和粗体显示为12px Arial。
因为隐式样式具有与其TargetType匹配的隐式x:Key ,所以你也可以继承它们:
<Style TargetType="TextBlock"> <Setter Property="FontSize" Value="12"/> <Setter Property="Foreground" Value="#FFBBBBBB" /> <Setter Property="FontFamily" Value="Arial" /> </Style> <Style x:Key="WarningTextBlockStyle" TargetType="TextBlock" BasedOn="{StaticResource {x:Type TextBlock}}"> <Setter Property="Foreground" Value="Red"/> <Setter Property="FontWeight" Value="Bold" /> </Style>