Search code examples
c#wpfwpfdatagridwpf-4.0

WPF Datagrid focus and highlighting last row


I would like to highlight my lastly new create row in my Data grid, I have reference this page http://social.technet.microsoft.com/wiki/contents/articles/21202.wpf-programmatically-selecting-and-focusing-a-row-or-cell-in-a-datagrid.aspx to get some idea.

According to the reference link above datagrid first have to visualise . The reason of the last row is not focus and high light, might be cause by this reason.

Following is my code structure

    private void CommitRow(object sender, DataGridRowEditEndingEventArgs e )
    {
          //FIRE WHEN ROW IS DONE EDIT
          /*
          STORING DATA TO DATABASE
          */

          SelectRowByIndex(Datagrid, Datagrid.Items.Count - 1); //I refer from msdn blog
    }

I tried to put the code SelectRowByIndex into a button , it will highlight the last row. Therefore I believe the code will only work when the grid is show up on UI.

My question is how to highlight the last row before interface is show up? or is that any other method allow me to focusing and high light the new create row?


Solution

  • You are correct, it cannot be highlighted, because it isn't rendered yet.

    But you can use the dispatcher to your advantage there.

     private void CommitRow(object sender, DataGridRowEditEndingEventArgs e )
        {
           //FIRE WHEN ROW IS DONE EDIT
           /*
           STORING DATA TO DATABASE
           */
    
        Dispatcher.BeginInvoke(DispatcherPriority.Input, new Action(() =>
        {
            SelectRowByIndex(Datagrid, Datagrid.Items.Count - 1);
        }));
     }
    

    This should do the trick. It calls the Dispatcher to do it with a priority thats just after rendering. Visually this should happen instantly.