WPF——样式

一、WPF样式

类似于Web应用程序中的CSS,在WPF中可以为控件定义统一的样式(Style)。样式属于资源的一种,例如为Button定义统一的背景颜色和字体:

  

 <Window.Resources>
<Style TargetType="Button">
<Setter Property="Background" Value="red" />
<Setter Property="Margin" Value="5" />
<Setter Property="FontFamily" Value="Comic Sans MS"/>
<Setter Property="FontSize" Value="14"/>
</Style>
<Style TargetType=" Button" x:Key="ButtonStyleC">
<Setter Property="Background" Value="Green" />
<Setter Property="Foreground" Value="Yellow" />
<Setter Property="FontSize" Value="28"/>
</Style>
</Window.Resources>
<StackPanel>
<Button>Button A</Button>
<Button Foreground="Red" Background="White">Button B</Button>
<Button Foreground="White" Background="Blue" Style="{StaticResource ButtonStyleC}" >Button C </Button>
<Button Style="{StaticResource ButtonStyleC}" Content="Button D" Height="53" Width="264">
<Button.Foreground>
<LinearGradientBrush StartPoint="0.5,0" EndPoint="0.5,1">
<LinearGradientBrush.GradientStops>
<GradientStop Offset="0.0" Color="#FFFFFF" />
<GradientStop Offset="1.0" Color="#0000FF" />
</LinearGradientBrush.GradientStops>
</LinearGradientBrush>
</Button.Foreground>
</Button>
</StackPanel>

 

从执行的结果上来看:

  • 在Style中定义的属性及值,影响到Window中的所有类型为Button的控件的样式
  • 在Button中可以新定义其他属性(如Foreground),覆盖Style中的定义(Background)

这种样式,类似于CSS中的类型选择器,为某种类型定义样式。

此外还可以在Style中加入x:Key属性,做为特定的样式(注意,这种也需要定义TargetType);定义时还可以基于已定义的某种样式,例如,基于刚才的Button的样式,更改字体的大小及文本的前景及背景颜色

posted @ 2012-03-16 16:44  Sam萨姆  阅读(1344)  评论(0编辑  收藏  举报