参考资料:
1. http://technet.microsoft.com/zh-cn/library/hh465374
2. http://msdn.microsoft.com/zh-cn/library/windows/apps/hh465045.aspx
先看下面我根据参考资料1修改后的代码,便于理解。
<!-- HH Add a new ControlTemplate for checkbox -->
<ControlTemplate x:Key="CheckBoxTemplate1" TargetType="CheckBox" >
<Border BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding
BorderThickness}" Background="{TemplateBinding Background}">
<VisualStateManager.VisualStateGroups>
<VisualStateGroup x:Name="CheckStates">
<VisualState x:Name="Checked">
<Storyboard>
<DoubleAnimation Duration="0" To="1"
Storyboard.TargetProperty="Opacity"
Storyboard.TargetName="CheckGlyph"/>
</Storyboard>
</VisualState>
<VisualState x:Name="Unchecked"/>
<VisualState x:Name="Indeterminate">
<Storyboard>
<DoubleAnimation Duration="0" To="1"
Storyboard.TargetProperty="Opacity"
Storyboard.TargetName="IndeterminateGlyph"/>
</Storyboard>
</VisualState>
</VisualStateGroup>
</VisualStateManager.VisualStateGroups>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
<RowDefinition Height="25"/>
</Grid.RowDefinitions>
<Rectangle x:Name="NormalRectangle" Fill="White" Stroke="Black"
StrokeThickness="1"
UseLayoutRounding="True" Height="21" Width="21"/>
<!-- Create an X to indicate that the CheckBox is selected. -->
<Path x:Name="CheckGlyph" Data="M103,240 L111,240 119,248 127,240 135,240 123,252
135,264 127,264 119,257 111,264 103,264 114,252 z"
Fill="Black" FlowDirection="LeftToRight" Height="14" Width="16" Opacity="0"
Stretch="Fill"/>
<!-- Create an Ellipse to indicate that the CheckBox is in an indeterminate
state. -->
<Ellipse x:Name="IndeterminateGlyph" Fill="Black" Height="12" Width="12"
Opacity="0"/>
<ContentPresenter Grid.Row="1"
x:Name="ContentPresenter" ContentTemplate="{TemplateBinding ContentTemplate}"
Content="{TemplateBinding Content}" Margin="{TemplateBinding
Padding}"
HorizontalAlignment="{TemplateBinding
HorizontalContentAlignment}"
VerticalAlignment="{TemplateBinding
VerticalContentAlignment}"/>
</Grid>
</Border>
</ControlTemplate>
具体实现的界面图,可以看参考资料1,那里面很详细。
注意点:
1. 请看Path以及Ellipse的Opacity属性值为0,表示默认情况下这2个属性不显示。
2. Storyboard表示控件模板中元素的外观。当控件切换到 VisualState.Name 属性指定的状态时,Storyboard 就会开
始。当控件退出该状态时,Storyboard 就会停止。
3. 当控件状态(即VisualState)切换到Checked的时候,Storyboard.TargetProperty="Opacity以及
Storyboard.TargetName="CheckGlyph"表示设置下面Grid的元素CheckGlyph中的Opacity为1,这样就将
CheckGlyph显示出来了。其他原理类似。
4.
Stroke :说明如何绘制形状的轮廓。
StrokeThickness :说明形状轮廓的粗细。
Fill :说明如何绘制形状的内部。
///
新手使用方法:
1. 新建一个Blank App(XAML),修改MainPage.xaml为:
<Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}">
<CheckBox Content="CheckBox" Template="{StaticResource CheckBoxTemplate1}" IsThreeState="True"
Margin="68,361,1223,328" Height="79"/>
</Grid>
2. 再将上述
<ControlTemplate ...> ... </<ControlTemplate >
部分代码添加到App.xaml中的<ResourceDictionary></ResourceDictionary>之间。