DataGrid : strange editing behaviour with DataGridTemplateColumn

Nov 13, 2008 at 10:50 AM

I have a DataGrid with two columns:
 <dg:DataGridTemplateColumn Header="Start" Width="100">
         <TextBlock Text="{Binding Name}" TextAlignment="Right" TextWrapping="Wrap"/>
         <TextBox Text="{Binding Name}" AcceptsReturn="True"  Padding="0" TextWrapping="Wrap"/>
<dg:DataGridTextColumn Header="- Name -" Width="200" Binding="{Binding LastName}" >

When I run the program the grid is displayed with data. I can use the arrow keys to move between cells. But when I want to edit cell data and press F2, this does not work properly with the TemplateColumn. The TextBox is displayed, but without a caret.I have to click the TextBox once with the mouse before I can enter any text.

The "normal" DataGridTExtColumn behaves as expected. F2 shows the TextBox, there is a caret and I can just type some text.

Norbert Ruessmann
Nov 13, 2008 at 1:13 PM
This is by design.  In the DataGridTextColumn, when a cell is opened for edit it will automatically set the caret.  For the DataGridTemplateColumn, it really can have any content in there so it cannot assume that it's a TextBox and try to set a caret.  If you want this behavior you will need to attach to the DataGrid.PreparingCellForEdit and set the caret yourself.  If you want to see how DataGridTextColumn does it, take a look at DataGridTextColumn.PrepareCellForEdit.

By the way, for DataGridTemplateColumn, if you want the edit to be committed you need to do something like this for the TextBox:

Text="{Binding Path=Name, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"