文章出處
文章列表
WPF中原始的CheckBox樣式很簡單,有時候不適用于WPF那種炫酷的界面。
本章節講述如何設計一個匹配業務需要、好看的CheckBox(繼上篇《WPF-自定義ListBox》中的CheckBox樣式)
CheckBox的樣式如下:
<Style x:Key="CheckBoxStyle" TargetType="{x:Type CheckBox}"> <Setter Property="SnapsToDevicePixels" Value="true" /> <Setter Property="OverridesDefaultStyle" Value="False" /> <Setter Property="FocusVisualStyle" Value="{DynamicResource CheckBoxFocusVisual}" /> <Setter Property="Template"> <Setter.Value> <ControlTemplate> <BulletDecorator> <BulletDecorator.Bullet> <Grid Height="{TemplateBinding Height}" Width="{TemplateBinding Width}"> <Border x:Name="Border"> <Rectangle Fill="DodgerBlue" RadiusY="5" RadiusX="5"></Rectangle> </Border> <Grid x:Name="CheckedMark"> <Path Visibility="Visible" Width="14" Height="14" SnapsToDevicePixels="False" StrokeThickness="2" Data="M1,6 L7,12"> <Path.Stroke> <SolidColorBrush Color="White" /> </Path.Stroke> </Path> <Path Visibility="Visible" Width="14" Height="14" SnapsToDevicePixels="False" StrokeThickness="2" Data="M6,12 L14,2"> <Path.Stroke> <SolidColorBrush Color="White" /> </Path.Stroke> </Path> </Grid> </Grid> </BulletDecorator.Bullet> <VisualStateManager.VisualStateGroups> <VisualStateGroup x:Name="CheckStates"> <VisualState x:Name="Checked"> <Storyboard> <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Visibility" Storyboard.TargetName="CheckedMark"> <DiscreteObjectKeyFrame KeyTime="0" Value="{x:Static Visibility.Visible}" /> </ObjectAnimationUsingKeyFrames> </Storyboard> </VisualState> <VisualState x:Name="Unchecked"> <Storyboard> <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Visibility" Storyboard.TargetName="CheckedMark"> <DiscreteObjectKeyFrame KeyTime="0" Value="{x:Static Visibility.Collapsed}" /> </ObjectAnimationUsingKeyFrames> </Storyboard> </VisualState> <VisualState x:Name="Indeterminate"> <Storyboard> <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Visibility" Storyboard.TargetName="CheckedMark"> <DiscreteObjectKeyFrame KeyTime="0" Value="{x:Static Visibility.Collapsed}" /> </ObjectAnimationUsingKeyFrames> </Storyboard> </VisualState> </VisualStateGroup> </VisualStateManager.VisualStateGroups> </BulletDecorator> </ControlTemplate> </Setter.Value> </Setter> </Style>
樣式中主要涉及CheckBox的模板,具體設計思路如下:
1、用一個裝飾控件BulletDecorator作為根節點
2、然后具體內容,用Retangle畫帶圓角的正方框,設置背景
3、畫倆條線,組裝成一個√
4、添加視覺顯示,這里用VisualStateManager來控制。當然用普通的觸發器Trigger也是可行的
如此樣式就設計好了。然后應用到實際的CheckBox中:
<CheckBox IsChecked="True" Height="20" Width="20" Style="{StaticResource CheckBoxStyle}" ></CheckBox>
是不是很簡單呢~哈哈
文章列表
全站熱搜