Search code examples
wpfxamldatagrid

DataGrid cells with large padding break row selection


I have set Padding to DataGrid cells as follows:

<Style x:Key="CellStyle" TargetType="{x:Type DataGridCell}">
    <Setter Property="Padding" Value="50" />
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type DataGridCell}">
                <Border Padding="{TemplateBinding Padding}">
                    <ContentPresenter />
                </Border>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

Padding applies fine, but the problem is that when I want to select the row if I click the empty space of the cell, the row isn't being selected. I have to click the actual text in the cell if I want to select the row.

How can this be fixed? I want to select row by mouse click anywhere inside the cell, be it empty space or text.

For example here I have a padding of 50 (I won't actually use 50 padding, but I want to illustrate the problem clearly): enter image description here

The row will be selected only if I click within the green box I want the row to be selected when I click anywhere in red box of any cell.


Solution

  • set some Background. default value is null. elements with null background do not register clicks/selection/etc

    <Style x:Key="CellStyle" TargetType="{x:Type DataGridCell}">
        <Setter Property="Padding" Value="50,2" />
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type DataGridCell}">
                    <Border Padding="{TemplateBinding Padding}" Background="Transparent">
                        <ContentPresenter />
                    </Border>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
    

    most likely later you will want to add Trigger, which will change Background for selected cells, so it is better to create binding for Background:

    <Style x:Key="CellStyle" TargetType="{x:Type DataGridCell}">
        <Setter Property="Padding" Value="50,2" />
        <Setter Property="Background" Value="Transparent" />
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type DataGridCell}">
                    <Border Padding="{TemplateBinding Padding}" Background="{TemplateBinding Background}">
                        <ContentPresenter />
                    </Border>
                    <ControlTemplate.Triggers>
                        <Trigger Property="IsSelected" Value="True">
                            <Setter Property="Background" Value="Blue" />
                        </Trigger>
                    </ControlTemplate.Triggers>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>