继续聊WPF——自定义CheckBox控件外观

上一篇文章中谈到了BulletDecorator控件,就是为自定义CheckBox控件的模板做准备,因为CheckBox需要比较严格的布局,正好,BulletDecorator控件就合适了,该控件的布局是有项目列表,排列起来好办很多了。
第一步,先建立一项资源,就是控件的聚焦样式,即当你在窗体中不断按Tab键使控件获取焦点时的样式,后面要用到。
<!--当控件获得键盘焦点时的样式--> <Style x:Key="FocusStyle"> <Setter Property="Control.Template"> <Setter.Value> <ControlTemplate> <Rectangle Stroke="Red" StrokeThickness="1"/> </ControlTemplate> </Setter.Value> </Setter> </Style>

第二步,写好CheckBox的样式。

<!-- CheckBox的样式 --> <Style TargetType="{x:Type CheckBox}"> <Setter Property="OverridesDefaultStyle" Value="True"/> <Setter Property="FocusVisualStyle" Value="{StaticResource FocusStyle}"/> <Setter Property="SnapsToDevicePixels" Value="True"/> <Setter Property="Foreground" Value="White"/> <Setter Property="FontSize" Value="16"/> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="{x:Type CheckBox}"> <BulletDecorator FlowDirection="LeftToRight" VerticalAlignment="Center"> <BulletDecorator.Bullet> <Border x:Name="bd" BorderThickness="1" BorderBrush="Red" MinHeight="15" MinWidth="15" VerticalAlignment="Center"> <Border.Background> <LinearGradientBrush StartPoint="0,0" EndPoint="1,1"> <GradientStop Color="LightGray" Offset="0.2"/> <GradientStop Color="White" Offset="1"/> </LinearGradientBrush> </Border.Background> <Path x:Name="cp" Width="12" Height="12" Stroke="Blue" StrokeThickness="3"/> </Border> </BulletDecorator.Bullet> <ContentPresenter Margin="2,0"/> </BulletDecorator> <!-- 控件触发器 --> <ControlTemplate.Triggers> <Trigger Property="IsChecked" Value="True"> <!-- 画上一个勾 --> <Setter TargetName="cp" Property="Data" Value="M 0,6 L 6,12 12,0"/> <Setter Property="Foreground" Value="LightGreen"/> </Trigger> <Trigger Property="IsMouseOver" Value="True"> <Setter TargetName="bd" Property="Background"> <Setter.Value> <LinearGradientBrush StartPoint="0,0" EndPoint="1,1"> <GradientStop Color="Orange" Offset="0.12"/> <GradientStop Color="Yellow" Offset="0.92"/> </LinearGradientBrush> </Setter.Value> </Setter> </Trigger> </ControlTemplate.Triggers> </ControlTemplate> </Setter.Value> </Setter> </Style>

第三步,把窗体默认的Grid控件去掉,为了更好地布局,应使用StatcPanel控件。
<StackPanel Orientation="Vertical" Margin="20,20,20,20"> <CheckBox Content="苹果"/> <CheckBox Content="鸡蛋"/> <CheckBox Content="白菜"/> <CheckBox Content="萝卜"/> <CheckBox Content="豆浆"/> <CheckBox Content="咸菜"/> <CheckBox Content="炒饭"/> <CheckBox Content="烧鸭饭"/> <CheckBox Content="叉烧饭"/> </StackPanel>


好,完事,现在来看看效果吧。

当项目被选中后,字体自动变为绿色,请参照上面的XAML代码。

怎么样,漂亮不?



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值