WPF样式类似于HTML中的CSS样式,设置外边距、内边距、颜色以及字体等细节,通过一系列封装所有这些细节的样式,然后再需要之处通过属性来应用样式。所以在设置WPF样式时,所花的时间也是比较多的。
WPF样式分为:
属性样式 直接通过UI元素的属性设置的样式
内联样式 通过在UI元素中嵌入style节点来设置样式
引用样式 定义在资源字典中的样式(页面级和应用程序级)
示例
属性样式,通过在TextBlock元素设置Width、Height、Margin等属性实现的简单样式
<Grid>
<!--属性样式-->
<TextBlock Text="textbox" Width="200" Height="50"
Margin="40,40,40,40" HorizontalAlignment="Center"
VerticalAlignment="Center" Background="Green" FontSize="36"
TextAlignment="Center">
</TextBlock>
</Grid>
内联样式,设置元素的style属性,也区分优先极,如果在元素里设置了内联样式又设置了属性的话会以属性样式为先
在TextBox里设置.style属性,TextBox里会使用.style的样式
<!--属性样式-->
<TextBox Text="textbox" Width="200" Height="50"
Margin="40,40,40,40" HorizontalAlignment="Center"
VerticalAlignment="Top" Background="SkyBlue" FontSize="36">
<!--内联样式-->
<TextBox.Style>
<!--Property指定控件属性-->
<Style TargetType="TextBox">
<Setter Property="Background" Value="Red"></Setter>
<Setter Property="BorderThickness" Value="3"></Setter>
<Setter Property="BorderBrush" Value="Yellow"></Setter>
</Style>
</TextBox.Style>
</TextBox>
引用样式,也就是资源定义,页面级引用的是整个页面都可以引用
<Window.Resources>
<Style x:Key="pbStyle" TargetType="TextBlock">
<Setter Property="FontSize" Value="40"></Setter>
<Setter Property="Background" Value="Transparent"></Setter>
<Setter Property="HorizontalAlignment" Value="Center"></Setter>
</Style>
</Window.Resources>
<Grid>
<TextBlock Style="{StaticResource pbStyle}" Text="页面引用" Height="60"></TextBlock>
</Grid>
应用程序级,需要在资源字典里定义,应用到整个程序
<Application.Resources>
<Style x:Key="btn" TargetType="{x:Type Button}">
<Setter Property="Background" Value="Black"></Setter>
<Setter Property="FontSize" Value="24"></Setter>
<Setter Property="Foreground" Value="Blue"></Setter>
<Setter Property="Margin" Value="20"></Setter>
</Style>
<Application.Resources/>
控件引用
<Button x:Name="button" Style="{StaticResource btn}" Content="Button" HorizontalAlignment="Left" Margin="122,10,0,0" VerticalAlignment="Top" Width="128" Height="57"/>
如果想在一个样式里面实现另一个样式的效果,就得使用Baseon来继承另一个样式
<Style x:Key="btn" TargetType="{x:Type Button}" BasedOn="{StaticResource btn}"/>
效果一致