gemGreg
gemGreg

Reputation: 194

DataGrid row selection not working when padding is added to cells

DataGrid control in WPF is behaving weird. When I click on a row it should be selected. There is a problem when I click on cell border or row border. It simply does nothing. As a user I want to click row and select it without forcing me to re-click cause I accidentally clicked on border between cells.

Is it possible to somehow fix this behavior so no matter where I click it selects row?


[edit]

I discovered its a matter of this style I applied to DataGrid to CellStyle property:

<Style x:Key="CustomDataGridCellStyle" TargetType="DataGridCell">
    <Setter Property="Padding" Value="2" />
    <Setter Property="Margin" Value="0" />
    <Setter Property="Background" Value="White" />
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="DataGridCell">
                <Border x:Name="border" 
                              BorderBrush="#CCaaccda"
                              BorderThickness="1"
                              CornerRadius="0"
                              Padding="4"
                            >
                    <ContentPresenter />
                </Border>
                <ControlTemplate.Triggers>
                    <DataTrigger Binding="{Binding RelativeSource={RelativeSource Self}, Path=IsSelected}" Value="true">
                        <Setter TargetName="border" Property="Background" Value="#CC119EDA"/>
                    </DataTrigger>
                </ControlTemplate.Triggers>
            </ControlTemplate>
        </Setter.Value>
    </Setter>   
</Style>

If I remove it its working. I wander how style can mess with interactions to control.


[edit]

Padding="4"

is preventing the created empty area between cells to not be able to take hit test. Any idea how to add not hittest blocking padding to cells?


[edit]

And the solution is very weird.

<Grid Background="Transparent" IsHitTestVisible="True">
    <ContentPresenter Margin="4"/>
</Grid>

Margin is added to cell content and its not reacting to click. But I surrounded it with Grid that have IsHitTestVisible="True" and is transparent. WPF is crazy weird.

Upvotes: 4

Views: 1651

Answers (1)

eran otzap
eran otzap

Reputation: 12533

Since you hadn't posted any xaml, or a picture of how your datagrid looks. It's hard to pint point the problem.

However, This might be caused by a Hit Test failing. The mouse hit test detects an element by the matrix of colored pixels which represent it.

Try coloring all the pixels by setting the background to Transparent. Transparent would not effect how your row looks and would color it for the Hit test :

<DataGrid>
    <DataGrid.RowStyle>
        <Style TargetType="DataGridRow">
            <Setter Property="Background" Value="Transparent" />
        </Style>
    </DataGrid.RowStyle>
</DataGrid>

Upvotes: 4

Related Questions