Search code examples
c#wpfdatagrid

Allow full row selection even if clicking on disabled cells in WPF Datagrid


I have a C# WPF Datagrid with some columns disabled (by applying IsEnabled=false style to the DataGridCell), so the cells are grayed and do not allow editing.

I need to allow full row selection on the grid even if the user clicks on that disabled cell ("Descr" in the sample below). Is this possible?

<DataGrid>
    <DataGrid.Columns>
        <DataGridTextColumn Header="Name" Binding="{Binding Name}"/>
        <DataGridTextColumn Header="Descr" Binding="{Binding Descr}">
            <DataGridTextColumn.CellStyle>
                <Style TargetType="DataGridCell">
                    <Setter Property="IsEnabled" Value="False" />
                </Style>
            </DataGridTextColumn.CellStyle>
        </DataGridTextColumn>
    </DataGrid.Columns>
</DataGrid>

Solution

  • You could handle the PreviewMouseLeftButtonDown event for the DataGridRow:

    <DataGrid x:Name="dg" SelectionUnit="FullRow">
        <DataGrid.RowStyle>
            <Style TargetType="DataGridRow">
                <EventSetter Event="PreviewMouseLeftButtonDown" Handler="dg_PreviewMouseLeftButtonDown" />
            </Style>
        </DataGrid.RowStyle>
        <DataGrid.Columns>
            <DataGridTextColumn Binding="{Binding}" />
            <DataGridTextColumn Binding="{Binding}">
                <DataGridTextColumn.CellStyle>
                    <Style TargetType="DataGridCell">
                        <Setter Property="IsEnabled" Value="False" />
                    </Style>
                </DataGridTextColumn.CellStyle>
            </DataGridTextColumn>
        </DataGrid.Columns>
    </DataGrid>
    
    private void dg_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
    {
        DataGridRow row = sender as DataGridRow;
        dg.SelectedItem = row.DataContext;
    }