【WPF】自定义CheckBox复选框
1 <Style x:Key="CheckBoxStyle" TargetType="{x:Type CheckBox}"> 2 <Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.ControlTextBrushKey}}"/> 3 <Setter Property="Background" Value="{StaticResource CheckRadioFillNormal}"/> 4 <Setter Property="BorderBrush" Value="{StaticResource CheckRadioStrokeNormal}"/> 5 <Setter Property="BorderThickness" Value="1"/> 6 <Setter Property="FocusVisualStyle" Value="{StaticResource EmptyCheckBoxFocusVisual}"/> 7 <Setter Property="Template"> 8 <Setter.Value> 9 <ControlTemplate TargetType="{x:Type CheckBox}"> 10 <BulletDecorator Background="Transparent" SnapsToDevicePixels="true"> 11 <BulletDecorator.Bullet> 12 <Border x:Name="cbd" BorderThickness="2" BorderBrush="LightBlue" MinHeight="30" MinWidth="30" VerticalAlignment="Center" Background="White"> 13 <Path x:Name="cp" Stroke="Lime" StrokeThickness="2" Width="25" Height="25" /> 14 </Border> 15 </BulletDecorator.Bullet> 16 <ContentPresenter HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" Margin="{TemplateBinding Padding}" RecognizesAccessKey="True" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}"/> 17 </BulletDecorator> 18 <ControlTemplate.Triggers> 19 <Trigger Property="IsChecked" Value="true" > 20 <Setter TargetName="cp" Property="Data" Value="M 0 17 L 7 25 M 7 27 L 27 0" /> 21 <Setter TargetName="cbd" Property="Background" Value="LightGray" /> 22 </Trigger> 23 <Trigger Property="HasContent" Value="true"> 24 <Setter Property="FocusVisualStyle" Value="{StaticResource CheckRadioFocusVisual}"/> 25 <Setter Property="Padding" Value="2,0,0,0"/> 26 </Trigger> 27 <Trigger Property="IsEnabled" Value="false"> 28 <Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.GrayTextBrushKey}}"/> 29 </Trigger> 30 <Trigger Property="IsMouseOver" Value="True"> 31 <Setter TargetName="cbd" Property="Background"> 32 <Setter.Value> 33 <LinearGradientBrush StartPoint="0.5,0" EndPoint="0.5,1"> 34 <GradientStop Color="LightGray" Offset="0.5" /> 35 <GradientStop Color="Silver" Offset="0.5" /> 36 </LinearGradientBrush> 37 </Setter.Value> 38 </Setter> 39 </Trigger> 40 </ControlTemplate.Triggers> 41 </ControlTemplate> 42 </Setter.Value> 43 </Setter> 44 </Style>
用到WPF中的CheckBox,发现默认的控件,勾选框奇小无比,无法通过设定宽高更改,只好自己研究一下怎么改模板,之前都是用Expression Blend改的,这回稍微认真地了解了一下。代码在上面。
最终效果可以引用CheckBoxStyle一下看看。
说明:
- Border为框,Path为勾,其他属性自己研究吧
- 效果如图,很丑