title: WPF DataGridView keyboard focus from command/viewmodel
body: <p>The net is full of similar questions and I searched SO as well (closest: [1], [2], [3]).</p>
  
  <p>So far I cannot believe that this problem is that ugly/non-trivial.</p>
  
  <p>I have a DataGridView. I have other controls (in this case: In the DataGridView's column headers). I want to support a quick 'jump to grid' command. This command needs to set the keyboard focus to the grid so that the user can use arrow keys to navigate between rows.</p>
  
  <p>Trivial testcase to play along at home below. It's insanely easy to select an element in the datagrid, but there doesn't seem to be a way to give it keyboard focus. Except in code-behind actions and even then it seems like you have to jump through hoops (see [2], juggling to get the cell container to set the keyboard focus, because .. grid and row doesn't seem to work from all I can tell).</p>
  
  <p>It seems simple enough?</p>
  
  <p>Some trivial model:</p>
  
  <pre><code>public class Item
  {
      public int DayOfMonth { get; set; }
      public string Weekday { get; set; }
  }
  </code></pre>
  
  <p>Matching trivial viewmodel (assumes that you have a RelayCommand implementation, see JumpToGrid for the ~meat~):</p>
  
  <pre><code>public class MainViewModel : INotifyPropertyChanged
  {
      public event PropertyChangedEventHandler PropertyChanged;
  
      private IList&lt;Item&gt; m_items;
      public IList&lt;Item&gt; SampleItems
      {
          get { return m_items; }
          set { SetField(ref m_items, value, () =&gt; SampleItems); }
      }
  
      private Item m_currentItem;
      public Item CurrentItem
      {
          get { return m_currentItem; }
          set { SetField(ref m_currentItem, value, () =&gt; CurrentItem); }
      }
  
      public ICommand JumpToGridCommand { get; private set; }
  
      public MainViewModel()
      {
          JumpToGridCommand = new RelayCommand(p =&gt; JumpToGrid());
  
          var items = new List&lt;Item&gt;();
          var today = DateTime.Now;
          for (int i = 1; i &lt;= DateTime.DaysInMonth(today.Year, today.Month); i++ )
          {
              items.Add(new Item { DayOfMonth = i, Weekday = new DateTime(today.Year, today.Month, i).DayOfWeek.ToString() });
          }
          SampleItems = items;
      }
  
      private void JumpToGrid()
      {
          // I can change the selection just fine
          CurrentItem = SampleItems[0];
  
          // But the keyboard focus is broken, up/down doesn't work as expected
      }
  
      protected bool SetField&lt;T&gt;(ref T field, T value, Expression&lt;Func&lt;T&gt;&gt; selectorExpression)
      {
          if (selectorExpression == null) throw new ArgumentNullException("selectorExpression");
          MemberExpression body = selectorExpression.Body as MemberExpression;
          if (body == null) throw new ArgumentException("The body must be a member expression");
          var fieldName = body.Member.Name;
  
          if (EqualityComparer&lt;T&gt;.Default.Equals(field, value)) return false;
          field = value;
          OnPropertyChanged(fieldName);
          return true;
      }
  
      protected void OnPropertyChanged(string propertyName)
      {
          PropertyChangedEventHandler handler = PropertyChanged;
          if (handler != null)
          {
              handler(this, new PropertyChangedEventArgs(propertyName));
          }
      }
  }
  </code></pre>
  
  <p>Simplistic view (code-behind is empty except for a "DataContext = new MainViewModel()" in the loaded event):
  <code>
  &lt;Window x:Class="DataGridKeyboardFocus.MainWindow"
          xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
          xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
          xmlns:local="clr-namespace:DataGridKeyboardFocus"
          Loaded="Window_Loaded"
          Title="MainWindow" Height="350" Width="525"&gt;
      &lt;Grid&gt;
          &lt;DataGrid
                  ColumnWidth="*" 
                  AutoGenerateColumns="False"
                  Margin="1"
                  ItemsSource="{Binding SampleItems}" 
                  SelectedItem="{Binding CurrentItem, Mode=TwoWay}"
                  SelectionUnit="FullRow"
                  IsReadOnly="True"&gt;
              &lt;DataGrid.Columns&gt;
                  &lt;DataGridTextColumn Binding="{Binding DayOfMonth}"&gt;
                      &lt;DataGridTextColumn.HeaderTemplate&gt;
                          &lt;DataTemplate&gt;
                          &lt;StackPanel Orientation="Vertical"&gt;
                              &lt;TextBlock Text="Some label" /&gt;
                              &lt;TextBox&gt;
                                  &lt;TextBox.InputBindings&gt;
                                      &lt;KeyBinding Modifiers="Control" Key="Tab" Command="{Binding DataContext.JumpToGridCommand, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type local:MainWindow}}}" /&gt;
                                  &lt;/TextBox.InputBindings&gt;
                              &lt;/TextBox&gt;
                          &lt;/StackPanel&gt;
                          &lt;/DataTemplate&gt;
                      &lt;/DataGridTextColumn.HeaderTemplate&gt;
                  &lt;/DataGridTextColumn&gt;
                  &lt;DataGridTextColumn Binding="{Binding Weekday}"&gt;
                      &lt;DataGridTextColumn.HeaderTemplate&gt;
                          &lt;DataTemplate&gt;
                              &lt;StackPanel Orientation="Vertical"&gt;
                                  &lt;TextBlock Text="Another label" /&gt;
                                  &lt;TextBox&gt;
                                      &lt;TextBox.InputBindings&gt;
                                          &lt;KeyBinding Modifiers="Control" Key="Tab" Command="{Binding DataContext.JumpToGridCommand, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type local:MainWindow}}}" /&gt;
                                      &lt;/TextBox.InputBindings&gt;
                                  &lt;/TextBox&gt;
                              &lt;/StackPanel&gt;
                          &lt;/DataTemplate&gt;
                      &lt;/DataGridTextColumn.HeaderTemplate&gt;
                  &lt;/DataGridTextColumn&gt;
              &lt;/DataGrid.Columns&gt;
          &lt;/DataGrid&gt;
      &lt;/Grid&gt;
  &lt;/Window&gt;
  </code></p>
  
  <p>1: <a href="https://stackoverflow.com/questions/1320816/keyboard-focus-vs-logical-focus-in-wpf">Keyboard focus vs logical focus in WPF</a></p>
  
  <p>2: <a href="https://stackoverflow.com/questions/20537073/wpf-datagrid-focus-and-keyboard-focus">Keyboard focus to DataGrid</a></p>
  
  <p>3: <a href="https://stackoverflow.com/questions/19248464/wpf-cant-control-keyboard-focus">WPF: Can&#39;t control keyboard focus</a></p>