如何将WPF复选框置于其可点击区域内?

Joe*_*ite 6 wpf checkbox

如果我在WPF中创建一个CheckBox控件(没有内容 - 我只需要检查/取消选中部分),它会将"框"视觉化(三维矩形中有或没有复选标记) )在控件的左上角.

我可以将"盒子"视觉放在CheckBox控件的中心吗?也就是说,水平和垂直居中?像这样的东西:

在此输入图像描述

通过将CheckBox的Horizo​​ntalAlignment和VerticalAlignment设置为Center,我可以获得与此类似的内容.这会导致CheckBox控件缩小到其"box"视觉的大小,然后在其父级中居中.然而,它只响应"盒子"视觉上的点击,这提供了一个更小,更不方便的目标.

svi*_*ick 0

您可以更改复选框的模板。最简单的方法是使用StyleSnooper之类的工具复制默认模板,然后根据您的需要将其编辑为如下所示:

<ControlTemplate>
  <BulletDecorator Background="Transparent">
    <aero:BulletChrome Width="13" Height="13" Background="{TemplateBinding Panel.Background}"
                       BorderBrush="{TemplateBinding Border.BorderBrush}" RenderMouseOver="{TemplateBinding UIElement.IsMouseOver}"
                       RenderPressed="{TemplateBinding ButtonBase.IsPressed}" IsChecked="{TemplateBinding ToggleButton.IsChecked}" />
  </BulletDecorator>
  <ControlTemplate.Triggers>
    <Trigger Property="ContentControl.HasContent" Value="True">
      <Setter Property="FrameworkElement.FocusVisualStyle">
        <Setter.Value>
          <Style TargetType="{x:Type IFrameworkInputElement}">
            <Setter Property="Control.Template">
              <Setter.Value>
                <ControlTemplate>
                  <Rectangle Stroke="{DynamicResource {x:Static SystemColors.ControlTextBrushKey}}"
                             StrokeThickness="1" StrokeDashArray="1 2" Margin="14,0,0,0" SnapsToDevicePixels="True" />
                </ControlTemplate>
              </Setter.Value>
            </Setter>
          </Style>
        </Setter.Value>
      </Setter>
      <Setter Property="Control.Padding" Value="4,0,0,0" />
    </Trigger>
    <Trigger Property="UIElement.IsEnabled" Value="False">
      <Setter Property="TextElement.Foreground" Value="{DynamicResource {x:Static SystemColors.GrayTextBrushKey}}" />
    </Trigger>
  </ControlTemplate.Triggers>
</ControlTemplate>
Run Code Online (Sandbox Code Playgroud)