3

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.

1 Answer 1

11

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>
4
  • Unfortunately, the DataGrid when you edit a cell and press Enter key, goes to the next row and also if you define IsTabStop=False, the focus goes on the cell and not to the templated inner control. It's strange, I know, and I'm facing this problem now, I the only way I see to resolve it is to handle the GotFocus DataGridCell event. Commented Nov 28, 2019 at 11:27
  • There are some questions 1 2 in this direction, not sure if they help you. If not, ask a new question, make sure to include the whole DataGrid definition, and maybe link to this and those two questions and specify why they don't work for you.
    – LWChris
    Commented Nov 29, 2019 at 13:27
  • The solution that you have provided it's OK to me for the problem asked, but I warned @j.kahil that this solution it's not enough for the Enter Key behaviour of any DataGrid For that problem I use to handle the GotFocus event. That's all Commented Dec 4, 2019 at 11:22
  • If you want Enter key to act as Tab, besides using the accepted answer you could take a look at this link (I couldn't post the code as is marked as too long): link In case the link stops working, search for EnterKeyTraversal . Add the class to your project and add EnterKeyTraversal.IsEnabled="True" at DataGrid to enable it.
    – John
    Commented Feb 15, 2020 at 0:04

Not the answer you're looking for? Browse other questions tagged or ask your own question.