wpf自定义复选框,文本内图标

时间:2014-09-23 20:25:56

标签: wpf xaml windows-phone-8

我是xaml的新人。我想创建带文本的自定义复选框,而不是默认选中标记。

[Yes] Accept Value    (checked state)
[No] Accept Value     (unchecked state)

我不想将图像用于"静态"文本。您能否转发给我一些样品或文章,其中包括以下范围。

1 个答案:

答案 0 :(得分:1)

为此,您可能需要修改默认控件模板。这是一个如何实现它的简单示例:

<!--x:Key="PhoneCheckBox"-->
<Style TargetType="CheckBox" x:Key="YesNoCheckBox">
  <Setter Property="Content" Value="Accept Value" />
  <Setter Property="Template">
    <Setter.Value>
      <ControlTemplate TargetType="CheckBox">
        <Grid Background="Transparent">

          <VisualStateManager.VisualStateGroups>
            <VisualStateGroup x:Name="CommonStates">
              <VisualState x:Name="Normal"/>
              <VisualState x:Name="MouseOver"/>
              <VisualState x:Name="Pressed" />
              <VisualState x:Name="Disabled" />
            </VisualStateGroup>
            <VisualStateGroup x:Name="CheckStates">
              <VisualState x:Name="Checked">
                <Storyboard>
                  <ObjectAnimationUsingKeyFrames Storyboard.TargetName="CheckText" Storyboard.TargetProperty="Text">
                    <DiscreteObjectKeyFrame KeyTime="0" Value="[Yes]" />
                  </ObjectAnimationUsingKeyFrames>
                </Storyboard>
              </VisualState>
              <VisualState x:Name="Unchecked" />
              <VisualState x:Name="Indeterminate" />
            </VisualStateGroup>
          </VisualStateManager.VisualStateGroups>

          <Grid Margin="{StaticResource PhoneTouchTargetLargeOverhang}">
            <Grid.ColumnDefinitions>
              <ColumnDefinition Width="32"/>
              <ColumnDefinition Width="*"/>
            </Grid.ColumnDefinitions>
            <Border x:Name="CheckBackground" IsHitTestVisible="False" VerticalAlignment="Center" HorizontalAlignment="Left" Background="{TemplateBinding Background}" BorderBrush="{TemplateBinding Background}" BorderThickness="{StaticResource PhoneBorderThickness}" Height="32" Width="32"/>
            <TextBlock x:Name="CheckText" Text="[No]" />
            <ContentControl x:Name="ContentContainer" Grid.Column="1" Content="{TemplateBinding Content}" ContentTemplate="{TemplateBinding ContentTemplate}" Margin="12,0,0,0" HorizontalContentAlignment="{TemplateBinding HorizontalContentAlignment}" VerticalContentAlignment="{TemplateBinding VerticalContentAlignment}" Padding="{TemplateBinding Padding}" Foreground="{TemplateBinding Foreground}" />
          </Grid>
        </Grid>
      </ControlTemplate>
    </Setter.Value>
  </Setter>
</Style>

我刚用TextBlock替换了复选符号,该符号在&#34; [是]&#34;之间切换。和#34; [No]&#34; (为简洁起见,还删除了&#34; Pressed&#34;,&#34; Disabled&#34;和&#34; Indeterminate&#34;视觉状态故事板)。

You can find the default control templates in your local SDK install.

要使用上述内容,只需引用样式键:

<CheckBox Style="{StaticResource YesNoCheckBox}" />