一.前言
申明:WPF自定义控件与样式是一个系列文章,前后是有些关联的,但大多是按照由简到繁的顺序逐步发布的等,若有不明白的地方可以参考本系列前面的文章,文末附有部分文章链接。
本文主要内容:
- CheckBox复选框的自定义样式,有两种不同的风格实现;
- RadioButton单选框自定义样式,有两种不同的风格实现;
二. CheckBox自定义样式
2.1 CheckBox基本样式
标准CheckBox样式代码如下,实现了三态的显示,其中不同状态的图标用了字体图标(关于字体图标,可以参考本文末尾附录链接)
<Style x:Key="DefaultCheckBox" TargetType="{x:Type CheckBox}">
<Setter Property="Background" Value="Transparent"></Setter>
<Setter Property="Foreground" Value="{StaticResource TextForeground}"></Setter>
<Setter Property="Padding" Value="0"></Setter>
<Setter Property="local:ControlAttachProperty.FIconMargin" Value="1, 1, 3, 1"></Setter>
<Setter Property="local:ControlAttachProperty.FIconSize" Value="22"></Setter>
<Setter Property="FontSize" Value="{StaticResource FontSize}"></Setter>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type CheckBox}">
<Grid x:Name="grid" Margin="{TemplateBinding Padding}" VerticalAlignment="Center">
<StackPanel Orientation="Horizontal" VerticalAlignment="Center">
<TextBlock x:Name="icon" Style="{StaticResource FIcon}" Text=""
FontSize="{TemplateBinding local:ControlAttachProperty.FIconSize}"
Margin="{TemplateBinding local:ControlAttachProperty.FIconMargin}"
Foreground="{TemplateBinding Foreground}"/>
<ContentPresenter VerticalAlignment="Center"/>
</StackPanel>
</Grid>
<!--触发器:设置选中状态符号-->
<ControlTemplate.Triggers>
<Trigger Property="IsChecked" Value="true">
<Setter Property="Text" Value="" TargetName="icon" ></Setter>
<Setter Property="Foreground" Value="{StaticResource CheckedForeground}"></Setter>
</Trigger>
<Trigger Property="IsChecked" Value="{x:Null}">
<Setter Property="Text" Value="" TargetName="icon" ></Setter>
</Trigger>
<Trigger Property="IsMouseOver" Value="true">
<Setter Property="Foreground" Value="{StaticResource MouseOverForeground}"></Setter>
</Trigger>
<Trigger Property="IsEnabled" Value="False">
<Setter Property="Opacity" Value="{StaticResource DisableOpacity}" TargetName="grid" ></Setter>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate