Search code examples
wpfdatagrid

Centering a checkbox in a WPF Datagrid


This seems like such a simple task, but I've gone round in circles, trying numerous approaches, but nothing I've tried works.

This is my column definition

<DataGridCheckBoxColumn Header="Select" Binding="{Binding IsSelected, UpdateSourceTrigger=PropertyChanged}" HeaderStyle="{StaticResource DGCHCentre}" Width="50" ElementStyle="{StaticResource LargerCheckBoxStyle}"/>

The DGCHCentre and LargerCheckBoxStyles are as follows

 <Style x:Key="DGCHCentre" TargetType="DataGridColumnHeader">
     <Setter Property="HorizontalContentAlignment" Value="Center" />
 </Style>
        <Style TargetType="CheckBox">
            <Setter Property="VerticalContentAlignment" Value="Center"/>
            <Setter Property="Height" Value="40"/>
            <Setter Property="FontSize" Value="14"/>
         </Style>

        <Style x:Key="LargerCheckBoxStyle" TargetType="{x:Type CheckBox}">
            <Setter Property="Width" Value="50" />
            <Setter Property="Height" Value="50" />
            <Setter Property="HorizontalAlignment" Value="Center"/>
            <Setter Property="HorizontalContentAlignment" Value="Center"/>
            <Setter Property="IsHitTestVisible" Value="False"/>
        </Style>

The checkbox is resolutely left-aligned in the column.

I've tried setting a margin

<Style x:Key="LargerCheckBoxStyle" TargetType="{x:Type CheckBox}">
    <Setter Property="Width" Value="50" />
    <Setter Property="Height" Value="50" />
    <Setter Property="HorizontalAlignment" Value="Center"/>
    <Setter Property="HorizontalContentAlignment" Value="Center"/>
    <Setter Property="IsHitTestVisible" Value="False"/>
    <Setter Property="Margin" Value="10 0 0 0"/>
</Style>

But this results in the left side of the checkbox disappearing.


Solution

  • Try setting the margin instead of the height and width in your style. In the example below, I am setting the margin to 25, which will add 25 to the top, bottom, left and right, and therefor center the checkbox while adding the additional space.

    <Style x:Key="LargerCheckBoxStyle" TargetType="{x:Type CheckBox}">
        <!-- Use the margin instead of height and width-->
        <Setter Property="Margin" Value="25" />
        <Setter Property="IsHitTestVisible" Value="False" />
    </Style>
    

    result

    enter image description here