Search code examples
wpfdatagrid

How to skip WPF DataGrid cell focus and go to control inside it?


In a WPF project I have a button in a DataGridCell. When I press tab it will focus the cell first and then the button inside this cell. How can I skip cell focus?

The columns are dynamic and I don't know which column has a button or textbox.


Solution

  • Since a button in a DataGrid is none of the standard column types, I suppose you're already using the DataGridTemplateColumn.

    Additionally to the DataGridTemplateColumn.CellTemplate, set the DataGridTemplateColumn.CellStyle with a style to set the DataGridCell.IsTabStop property to False:

    <DataGrid ItemsSource="{Binding Items}" AutoGenerateColumns="False">
        <DataGrid.Columns>
            <DataGridCheckBoxColumn Binding="{Binding IsChecked}" Header="CheckBoxColumn" />
            <DataGridTextColumn Binding="{Binding Text}" Header="TextColumn" />
            <DataGridTemplateColumn Header="ButtonColumn">
                <DataGridTemplateColumn.CellTemplate>
                    <DataTemplate>
                        <Button Content="Text" />
                    </DataTemplate>
                </DataGridTemplateColumn.CellTemplate>
                <DataGridTemplateColumn.CellStyle>
                    <Style TargetType="DataGridCell">
                        <Setter Property="IsTabStop" Value="False" />
                    </Style>
                </DataGridTemplateColumn.CellStyle>
            </DataGridTemplateColumn>
        </DataGrid.Columns>
    </DataGrid>