wpf - 如何将 WPF 复选框置于其可点击区域的中心?

标签 wpf checkbox

如果我在 WPF 中创建一个 CheckBox 控件(没有内容 - 我只需要选中/取消选中部分),它会放置“框”视觉对象(具有或不具有选中状态的 3D 矩形)标记)在控件的左上角。

我可以将“box”视觉对象放在 CheckBox 控件的中心吗?也就是说,水平和垂直居中?像这样的事情:

enter image description here

通过将复选框的 Horizo​​ntalAlignment 和 VerticalAlignment 设置为 Center,我可以获得与此类似的视觉效果。这会导致 CheckBox 控件缩小到其“框”视觉效果的大小,然后在其父控件中居中。然而,它只响应对“盒子”视觉效果的点击,这呈现了一个更小且更不方便的目标。

最佳答案

您可以更改复选框的模板。最简单的方法是使用类似 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>

关于wpf - 如何将 WPF 复选框置于其可点击区域的中心?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6077510/

相关文章:

c# - 在 ConverterParameter 中使用反斜杠

javascript - 将 Meteor 复选框状态与数据库同步

php - 我如何获取、查看和更新​​存储在数据库中的复选框值

c# - 添加了 MRU 项的 WPF 组合框

c# - 访问样式元素

java - 如何在 Android 中使用复选框管理布局

javafx - 未选中复选框时如何停止转换javafx

Django - 复选框数组

c# - 如何在 wpf 对话框中选择默认按钮?

c# - 如何仅从 WPF MVVM 中的调度程序线程以外的线程更新可观察集合中的属性?