WPF and Silverlight学习笔记(十八):WPF样式(Style)与模板(Template)2010-12-17 博客园 龙腾于海一、WPF样式类似于Web应用程序中的CSS,在WPF中可以为控件定义统 一的样式(Style)。样式属于资源的一种,例如为Button定义统一的背景颜色 和字体:
1: <Window.Resources>
2: <Style
3: TargetType="Button">
4: <Setter Property="Background" Value="Yellow" />
5: <Setter Property="Margin" Value="5" />
6: <Setter Property="FontFamily" Value="Comic Sans MS"/>
7: <Setter Property="FontSize" Value="14"/>
8: </Style>
9: </Window.Resources>
10: <StackPanel>
11: <Button>Button A</Button>
12: <Button Foreground="Red" Background="White">Button B</Button>
13: </StackPanel>

从执行的结果上来看:在Style中定义的属性及值,影响到 Window中的所有类型为Button的控件的样式在Button中可以新定义其他 属性(如Foreground),覆盖Style中的定义(Background)这种样式, 类似于CSS中的类型选择器,为某种类型定义样式。此外还可以在Style 中加入x:Key属性,做为特定的样式(注意,这种也需要定义TargetType);定 义时还可以基于已定义的某种样式,例如,基于刚才的Button的样式,更改字体 的大小及文本的前景及背景颜色:
1: <Window.Resources>
2: <Style
3: TargetType="Button">
4: <Setter Property="Background" Value="Yellow" />
5: <Setter Property="Margin" Value="5" />
6: <Setter Property="FontFamily" Value="Comic Sans MS"/>
7: <Setter Property="FontSize" Value="14"/>
8: </Style>
9: <Style
10: TargetType="Button"
11: x:Key="ButtonStyleA"
12: BasedOn=" {StaticResource {x:Type Button}}">
13: <Setter Property="Background" Value="Green" />
14: <Setter Property="Foreground" Value="Yellow" />
15: <Setter Property="FontSize" Value="28"/>
16: </Style>
17: </Window.Resources>
18: <StackPanel>
19: <Button>Button A</Button>
20: <Button Foreground="Red" Background="White">Button B</Button>
21: <Button Style="{StaticResource ButtonStyleA} ">Button C</Button>
22: <Button Style="{StaticResource ButtonStyleA}" Content="Button D">
23: <Button.Foreground>
24: <LinearGradientBrush StartPoint="0.5,0" EndPoint="0.5,1">
25: <LinearGradientBrush.GradientStops>
26: <GradientStop Offset="0.0" Color="#FFFFFF" />
27: <GradientStop Offset="1.0" Color="#0000FF" />
28: </LinearGradientBrush.GradientStops>
29: </LinearGradientBrush>
30: </Button.Foreground>
31: </Button>
32: </StackPanel>