.NET · Visual Studio · WPF

WPF datagrid focus on cell

There is a lot of questions out there on how to focus on a particular cell in a WPF application.

If you have the data in you datagrid updated from somewhere else, maybe from SignalR or just updating your Observable object from somewhere in your application, and you want to focus that particular row and that particular property in you grid, you can do it this way:

This could be on a button click event f.ex:

yourdatagrid.UpdateLayout();
yourdatagrid.ScrollIntoView(yourObject, yourColomn);
yourdatagrid.Focus();
if (yourdatagrid.SelectedItem != null)
   {
    var cellcontent = yourdatagrid.Columns[yourColomn.DisplayIndex].GetCellContent(yourdatagrid.SelectedItem);
    var cell = cellcontent?.Parent as DataGridCell;
    if (cell != null)
       {
          cell.Focus();
       }
   }

Download the code here

Thanks for reading.