Question

I'm using an AutoCompleteBox from the WPF Toolkit inside a DataGridTemplateColumn's editing template in WPF4. It works well enough for the most part once I sorted out all the niggling binding issues around DataGrid binding and also AutoCompleteBox's own gotchas and incompleteness. So far so good. The problem is keyboard navigation.

This is the scenario: there's a DataGrid with two columns. The first is a DataGridTemplateColumn which has an AutoCompleteBox in its editing template. The second is just an ordinary DataGridTextColumn.

If I invoke editing of a row, I can choose an item in the AutoCompleteBox. I press tab to move to the next column, but instead the row edit gets committed, and the keyboard focus doesn't move to the next column. If this was a DataGridTextColumn, it would stay in edit mode and let me edit the next column. This also happens for new rows.

To my mind it seems like there's something wrong with where WPF decides to send the keyboard focus when it comes out of the Autocompletebox, but I can't figure out what I can do about it, and I also haven't been able to find anybody talking about the same problem, which suggests either I'm doing something wrong or nobody else cares about keyboard navigation through their grids. I have been using a TemplateColumn subclass which overrides PrepareCellForEditing to ensure the focus lands in the AutoCompleteBox immediately on editing the cell (as per other answers here), but the problem persists if I disable all that code so it's not an effect of that bit of trickery as far as I can tell.

Any ideas?

The XAML looks more or less like this (simplified, of course, the grid has a lot more than two columns and some rather complicated data binding going on - I've left out the bindings and kept it to the overall structure).

<DataGrid>
  <DataGridTemplateColumn Header="AutoCompleteBox">
    <DataGridTemplateColumn.CellTemplate>
      <DataTemplate><TextBlock /></DataTemplate>
    </DataGridTemplateColumn.CellTemplate>
    <DataGridTemplateColumn.CellEditingTemplate>
      <DataTemplate>
        <toolkit:AutoCompleteBox>
          <!-- autocompletebox's item template etc. -->
        </toolkit:AutoCompleteBox>
      </DataTemplate>
    </DataGridTemplateColumn.CellEditingTemplate>
  </DataGridTemplateColumn>
  <DataGridTextColumn Header="Text" />
</DataGrid>
Was it helpful?

Solution

For moving focus to the next column I've made extended class (tab works fine for me):

public class ExAutoCompleteBox : AutoCompleteBox
{
        public ExAutoCompleteBox()
        {
            PreviewKeyUp += (o, e) =>
            {
                if (e.Key == Key.Enter)
                {
                    ((UIElement)Keyboard.FocusedElement).MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));
                }
            };
        }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top