How can I center a WPF checkbox inside its clickable region?
If I create a CheckBox control in WPF (with no Content -- I only need the check/uncheck part), it puts the "box" visual (the 3-D rectangle that either has or doesn't have a check mark in it) in the top-left corner of the control.
Can I put the "box" visual in the center of the CheckBox control instead? That is,开发者_JS百科 centered both horizontally and vertically? Something like this:
I can get something visually similar to this by setting the CheckBox's HorizontalAlignment and VerticalAlignment to Center. This causes the CheckBox control to shrink to just the size of its "box" visual, and then that gets centered within its parent. However, then it only responds to clicks on the "box" visual, which presents a much smaller and more inconvenient target.
You can change the template of the checkbox. The easiest way is to copy the default template using something like StyleSnooper and then edit it for your needs to something like this:
<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>
精彩评论