上一篇文章中谈到了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代码。
怎么样,漂亮不?