Making a row non-focusable in a WPF datagrid

2020-03-25 07:35发布

问题:

I'm trying to figure out how to make the rows in the following WPF DataGrid non-focusable. As you can see I tried adding a <DataGrid.Resources> section to the DataGrid where I'm specifying a DataGrid cell style but this isn't working. What am I missing?

<DataGrid Name="grdResources"
AutoGenerateColumns="False" SelectionUnit="FullRow"
AlternatingRowBackground="LightBlue" CanUserDeleteRows="False" CanUserAddRows="False"
CanUserReorderColumns="False" ClipboardCopyMode="ExcludeHeader">

<DataGrid.Resources>
    <DataGridTemplateColumn.CellStyle>
        <Style TargetType="DataGridCell">
            <Setter Property="Focusable" Value="False"/>
        </Style>
    </DataGridTemplateColumn.CellStyle>
</DataGrid.Resources>

<DataGrid.Columns>
    <DataGridTemplateColumn Header="Select" IsReadOnly="True" >
        <DataGridTemplateColumn.CellTemplate>
            <DataTemplate>
                <CheckBox Name="Select" Tag="{Binding}" Click="Select_Click"/>
            </DataTemplate>
        </DataGridTemplateColumn.CellTemplate>
    </DataGridTemplateColumn>

    <DataGridTemplateColumn Header="Key" IsReadOnly="True">
        <DataGridTemplateColumn.CellTemplate >
            <DataTemplate>
                <Label Content="{Binding Path=Key}"></Label>
            </DataTemplate>
        </DataGridTemplateColumn.CellTemplate>
    </DataGridTemplateColumn>

    <DataGridTemplateColumn Header="Value" IsReadOnly="True">
        <DataGridTemplateColumn.CellTemplate >
            <DataTemplate>
                <TextBlock TextWrapping="Wrap" Text="{Binding Path=Value}"/>
            </DataTemplate>
        </DataGridTemplateColumn.CellTemplate>
    </DataGridTemplateColumn>
</DataGrid.Columns>

EDIT For those interested I ended up overriding the SelectedRow style so it doesn't highlight the row when selected. Here is my <DataGrid.Resources> section after that change:

    <DataGrid.Resources>
        <Style TargetType="{x:Type DataGridCell}">
            <Style.Triggers>
                <Trigger Property="IsSelected" Value="True">
                    <Setter Property="Background" Value="Transparent"/>
                    <Setter Property="Foreground" Value="Black"/>
                    <Setter Property="BorderBrush" Value="Transparent"/>
                    <Setter Property="BorderThickness" Value="1"/>
                </Trigger>
            </Style.Triggers>
        </Style>
    </DataGrid.Resources>

回答1:

Use IsHitTestVisible = False

<DataGrid.Resources>
    <Style x:Key="NoFocusColumStyle" TargetType="{x:Type DataGridCell}">
        <Setter Property="IsHitTestVisible" Value="False"/>
    </Style>
</DataGrid.Resources>

Then apply the style to whatever columns you want to restrict focus for

<DataGridTextColumn CellStyle="{StaticResource NoFocusColumStyle}" ... />