0

I am struggling from this probelem of focusing the TextBox present inside the DataGrid. The real scenario is:

I have a DataGrid in which I have 3 columns.The 3rd column of the DataGrid contains 2 different controls:- one is ComboBox and the other one is TextBox(Both are in the same RowDefinition and ColumnDefinition). Suppose I have 3 rows so what is want is When I enter a text in the Textbox(present in first row) and press ENTER then the focus should move to the next row TEXTBOX,But what is happening right now is It focuses the Whole cell(which contains both ComboBox and TextBox) of the DataGrid.

I tried couple of examples :

 private void dg_PreviewKeyDown(object sender, KeyEventArgs e)
        {
              var uie = e.OriginalSource as UIElement;

                if (e.Key == Key.Enter)
                {
                    e.Handled = true;
                    uie.MoveFocus(
                    new TraversalRequest(FocusNavigationDirection.Next));


                }

            }

but it moves focus on the next CELL which is same as Focusing cell with both ComoBox and TextBox.

I followed this link too but it dint help:

http://madprops.org/blog/enter-to-tab-as-an-attached-property/

Help me out Guys..Focusing controls always BUGS ME.

Vishal
  • 604
  • 1
  • 12
  • 25

1 Answers1

0

I finally found the solution for this:

Here is the code which helped me to move focus on enter key:

Note: UCItems is the collection which is Bind to the DataGrid

private void dg_PreviewKeyDown(object sender, KeyEventArgs e)
        {

                if (e.Key == Key.Enter)
                {
                    DataGridRow rowContainer = (DataGridRow)BomPickerGrid.ItemContainerGenerator.ContainerFromItem(UCItems[gridIndex+1]);
                    if (rowContainer != null)
                    {
                        DataGridCellsPresenter presenter = FindVisualChild<DataGridCellsPresenter>(rowContainer);
                        int columnIndex = BomPickerGrid.Columns.IndexOf(BomPickerGrid.CurrentColumn);
                        DataGridCell cell = (DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(columnIndex);
                        TraversalRequest request = new TraversalRequest(FocusNavigationDirection.Last);
   /* FocusNavigationDirection.Last is used because the 
TextBox I want to focus on is the Last control in that Cell*/
                                request.Wrapped = true;
                                cell.MoveFocus(request);
                                rowContainer = (DataGridRow)BomPickerGrid.ItemContainerGenerator.ContainerFromItem(BomPickerGrid.CurrentItem);
                                BomPickerGrid.SelectedItem = BomPickerGrid.CurrentItem;
                                e.Handled = true;
                                BomPickerGrid.UpdateLayout();
                            }
                        }
Vishal
  • 604
  • 1
  • 12
  • 25