Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to focus cell on new row in WPF DataGrid

.Net 4 WPF DataGrid MVVM

User clicks add button which triggers command on viewmodel. In the viewmodel command execute, I add a new object to the viewcollection of the viewmodel that the grid is bound to. The new row does appear in my grid. However, I also want to send the focus to the first editable cell in that new row.

I even "cheated" mvvm, added an event on my viewmodel that the view listens to, to know when to focus the new row.

I've searched but no luck. I was hopeful when I came across this:

Datagrid Set focus on newly added row

which leads to

http://social.msdn.microsoft.com/forums/en-US/wpf/thread/63974f4f-d9ee-45af-8499-42f29cbc22ae

But the problem that others have reported and no one has answered is how to deal with the virtualizing behaviour of the grid. The newly added row has not yet been created. So that GetCells call fails frequently. And if ScrollIntoView is required, then it's that much more likely to fail.

I've hooked a ton of events including LoadingRow and RequestBringIntoView with no luck. Depending on which event I hook, I have managed to be able to get a reference to the cell. But then I get an error "Cannot call StartAt when content generation is in progress". But I checked the status of the ItemContainerGenerator and it was ContainersGenerated when I made the call to the cell's BeginEdit.

like image 653
happyfirst Avatar asked Nov 14 '22 09:11

happyfirst


1 Answers

Here is one way to set focus to a particular cell programmatically:

DataGridCell cell = GetCell(rowIndex, colIndex);
cell.Focus;

Please see the following article for more information on GetCell().

like image 109
Dmitry Savy Avatar answered Nov 16 '22 04:11

Dmitry Savy