【问题标题】:How can I center a WPF checkbox inside its clickable region?如何在其可点击区域内居中 WPF 复选框?
【发布时间】:2011-08-29 23:15:09
【问题描述】:

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

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

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

【问题讨论】:

  • 一种选择是将复选框扩展到整个可用的using ViewBox。诚然,这看起来很奇怪。

标签: wpf checkbox


【解决方案1】:

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

【讨论】:

  • 该示例在 .NET 4 中不太适用,但我采用了与运行 StyleSnooper 相同的方法并让它运行起来。您需要在项目引用中包含 PresentationFramework.Aero,添加几个所需的命名空间,删除 ContentPresenter 并将 BulletChrome 元素移动到 BulletDecorator 的正下方。主要问题是即使用户使用不同的主题,他们总是会得到 Aero 主题复选框。
猜你喜欢
  • 2013-07-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-12-10
  • 2011-05-06
相关资源
最近更新 更多