title: How to select and set focus a datagrid row programmatically using MVVM design pattern in WPF
body: <p>I have a simple WPF application that has a data grid. What I want is to select and set focus data grid row once I click a button. When the row is selected, I need to change the selected (focused) row using keyboard up/down arrow keys. 
  <strong>Most impotent thing is, I want to do this in MVVM design pattern.</strong>
  My application is as below.</p>
  
  <p><code>Item.cs</code> model is as below:</p>
  
  <pre><code>public class Item
  {
      public string ItemCode { get; set; }
      public string ItemName { get; set; }
      public double ItemPrice { get; set; }
  
      public Item(string itemCode, string itemName, double itemPrice)
      {
          this.ItemCode = itemCode;
          this.ItemName = itemName;
          this.ItemPrice = itemPrice;
      }
  }
  </code></pre>
  
  <p><code>ItemViewModel.cs</code> is as below:</p>
  
  <pre><code>public class ItemsViewModel : INotifyPropertyChanged
  {
      private List&lt;Item&gt; _items;
  
      public List&lt;Item&gt; ItemsCollection
      {
          get { return this._items; }
          set
          {
              _items = value;
              OnPropertyChanged(nameof(ItemsCollection));
          }
      }
  
      public ItemsViewModel()
      {
          this.ItemsCollection = new List&lt;Item&gt;();
          //Add default items
          this.ItemsCollection.Add(new Item("I001", "Text Book", 10));
          this.ItemsCollection.Add(new Item("I002", "Pencil", 20));
          this.ItemsCollection.Add(new Item("I003", "Bag", 15));
      }
  
      public event PropertyChangedEventHandler PropertyChanged;
  
      protected virtual void OnPropertyChanged(string propertyName)
      {
          if (this.PropertyChanged != null)
              this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
      }
  }
  </code></pre>
  
  <p><code>MainWindowViewModel.cs</code> as below:</p>
  
  <pre><code>public class MainWindowViewModel : INotifyPropertyChanged
  {
      public ICommand SelectRow { get; private set; }
  
      public MainWindowViewModel()
      {
          this.SelectRow = new RelayCommand(this.SelectGridRow, o =&gt; true);
      }
  
      private void SelectGridRow(object param)
      {
          //TODO: Code should goes here
      }
  
      public event PropertyChangedEventHandler PropertyChanged;
  
      protected virtual void OnPropertyChanged(string propertyName)
      {
          if (this.PropertyChanged != null)
              this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
      }
  }
  </code></pre>
  
  <p>I have written following <code>RelayCommand.cs</code> to handle the command binding.</p>
  
  <pre><code>public class RelayCommand : ICommand
  {
      #region Fields
  
      /// &lt;summary&gt;
      /// Encapsulated the execute action
      /// &lt;/summary&gt;
      private Action&lt;object&gt; execute;
  
      /// &lt;summary&gt;
      /// Encapsulated the representation for the validation of the execute method
      /// &lt;/summary&gt;
      private Predicate&lt;object&gt; canExecute;
  
      #endregion // Fields
  
      #region Constructors
  
      /// &lt;summary&gt;
      /// Initializes a new instance of the RelayCommand class
      /// Creates a new command that can always execute.
      /// &lt;/summary&gt;
      /// &lt;param name="execute"&gt;The execution logic.&lt;/param&gt;
      public RelayCommand(Action&lt;object&gt; execute)
          : this(execute, DefaultCanExecute)
      {
      }
  
      /// &lt;summary&gt;
      /// Initializes a new instance of the RelayCommand class
      /// Creates a new command.
      /// &lt;/summary&gt;
      /// &lt;param name="execute"&gt;The execution logic.&lt;/param&gt;
      /// &lt;param name="canExecute"&gt;The execution status logic.&lt;/param&gt;
      public RelayCommand(Action&lt;object&gt; execute, Predicate&lt;object&gt; canExecute)
      {
          if (execute == null)
          {
              throw new ArgumentNullException("execute");
          }
  
          if (canExecute == null)
          {
              throw new ArgumentNullException("canExecute");
          }
  
          this.execute = execute;
          this.canExecute = canExecute;
      }
  
      #endregion // Constructors
  
      #region ICommand Members
  
      /// &lt;summary&gt;
      /// An event to raise when the CanExecute value is changed
      /// &lt;/summary&gt;
      /// &lt;remarks&gt;
      /// Any subscription to this event will automatically subscribe to both 
      /// the local OnCanExecuteChanged method AND
      /// the CommandManager RequerySuggested event
      /// &lt;/remarks&gt;
      public event EventHandler CanExecuteChanged
      {
          add
          {
              CommandManager.RequerySuggested += value;
              this.CanExecuteChangedInternal += value;
          }
  
          remove
          {
              CommandManager.RequerySuggested -= value;
              this.CanExecuteChangedInternal -= value;
          }
      }
  
      /// &lt;summary&gt;
      /// An event to allow the CanExecuteChanged event to be raised manually
      /// &lt;/summary&gt;
      private event EventHandler CanExecuteChangedInternal;
  
      /// &lt;summary&gt;
      /// Defines if command can be executed
      /// &lt;/summary&gt;
      /// &lt;param name="parameter"&gt;the parameter that represents the validation method&lt;/param&gt;
      /// &lt;returns&gt;true if the command can be executed&lt;/returns&gt;
      public bool CanExecute(object parameter)
      {
          return this.canExecute != null &amp;&amp; this.canExecute(parameter);
      }
  
      /// &lt;summary&gt;
      /// Execute the encapsulated command
      /// &lt;/summary&gt;
      /// &lt;param name="parameter"&gt;the parameter that represents the execution method&lt;/param&gt;
      public void Execute(object parameter)
      {
          this.execute(parameter);
      }
  
      #endregion // ICommand Members
  
      /// &lt;summary&gt;
      /// Raises the can execute changed.
      /// &lt;/summary&gt;
      public void OnCanExecuteChanged()
      {
          EventHandler handler = this.CanExecuteChangedInternal;
          if (handler != null)
          {
              //DispatcherHelper.BeginInvokeOnUIThread(() =&gt; handler.Invoke(this, EventArgs.Empty));
              handler.Invoke(this, EventArgs.Empty);
          }
      }
  
      /// &lt;summary&gt;
      /// Destroys this instance.
      /// &lt;/summary&gt;
      public void Destroy()
      {
          this.canExecute = _ =&gt; false;
          this.execute = _ =&gt; { return; };
      }
  
      /// &lt;summary&gt;
      /// Defines if command can be executed (default behaviour)
      /// &lt;/summary&gt;
      /// &lt;param name="parameter"&gt;The parameter.&lt;/param&gt;
      /// &lt;returns&gt;Always true&lt;/returns&gt;
      private static bool DefaultCanExecute(object parameter)
      {
          return true;
      }
  }
  </code></pre>
  
  <p>I have a <code>ItemView.xaml</code> User control as below:</p>
  
  <pre><code>&lt;UserControl x:Class="DataGrid_FocusRow.ItemView"
           xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
           xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
           xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
           xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
           xmlns:local="clr-namespace:DataGrid_FocusRow"
           mc:Ignorable="d" 
           d:DesignHeight="450" d:DesignWidth="800"&gt;
  &lt;Grid&gt;
      &lt;StackPanel Orientation="Vertical"&gt;
          &lt;DataGrid x:Name="grdItems" ItemsSource="{Binding ItemsCollection}" AutoGenerateColumns="False" ColumnWidth="*"&gt;
              &lt;DataGrid.Columns&gt;
                  &lt;DataGridTextColumn Header="Item Code" Binding="{Binding ItemCode}" /&gt;
                  &lt;DataGridTextColumn Header="Item Name" Binding="{Binding ItemName}" /&gt;
                  &lt;DataGridTextColumn Header="Item Price" Binding="{Binding ItemPrice}" /&gt;
              &lt;/DataGrid.Columns&gt;
          &lt;/DataGrid&gt;
      &lt;/StackPanel&gt;
  &lt;/Grid&gt;
  </code></pre>
  
  <p></p>
  
  <p>My <code>MainWindow.xaml</code> is as below:</p>
  
  <pre><code>&lt;Window x:Class="DataGrid_FocusRow.MainWindow"
      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
      xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
      xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
      xmlns:local="clr-namespace:DataGrid_FocusRow"
      mc:Ignorable="d"
      Title="MainWindow" Height="450" Width="800"&gt;
  &lt;StackPanel&gt;
      &lt;local:ItemView/&gt;
  
      &lt;Button Command="{Binding SelectRow}"&gt;Select Row&lt;/Button&gt;
  &lt;/StackPanel&gt;
  </code></pre>
  
  <p></p>
  
  <p>Can someone please help me with this.</p>
  
  <blockquote>
    <p>Update: I've already tried by setting "SelectedIndex" and "SelectedItem". It selects the row in the data grid. But it does not set focus to the particular row. Because of that I cannot change the selection by UP/DOWN keys in my keyboard.</p>
  </blockquote>