title: Automatic editing of WPF datagrid content when datagrid-cell gets focus
body: <p>I have a datagrid in WPF with a <strong>DataGridTextColum</strong> and a <strong>DataGridTemplateColum</strong>.</p>
  
  <pre><code>&lt;DataGridTextColumn Width="4*" IsReadOnly="True" x:Name="dataGridColumnDescription" 
  Header="Description" Binding="{Binding Description}"&gt;
  &lt;/DataGridTextColumn&gt;
  
  &lt;DataGridTemplateColumn CellStyle="{StaticResource CellEditing}" IsReadOnly="False" Width="*" Header="Value" 
  CellEditingTemplateSelector="{StaticResource myCellEditingTemplateSelectorValue}" 
  CellTemplateSelector="{StaticResource myCellTemplateSelectorValue}"&gt;
  &lt;/DataGridTemplateColumn&gt;
  </code></pre>
  
  <p>The CellTemplateSelectors return a DataTemplate with a TextBlock for the the Celltemplate resp. a TextBox for CellEditing!</p>
  
  <pre><code>&lt;DataTemplate x:Key="dGridStringValueTemplate"&gt;
      &lt;TextBlock HorizontalAlignment="Center" VerticalAlignment="Center" Text="{Binding Path=Value}"/&gt;
  &lt;/DataTemplate&gt;
  
  &lt;DataTemplate x:Key="dGridStringValueTemplateEditing"&gt;
      &lt;TextBox TextAlignment="Center" VerticalAlignment="Center" VerticalContentAlignment="Center" HorizontalContentAlignment="Center" BorderThickness="1" Text="{Binding Path=Value, UpdateSourceTrigger=LostFocus}"/&gt;
  &lt;/DataTemplate&gt;
  </code></pre>
  
  <p><strong>Now I want to automatically Focus the TextBox when the DataGridCell gets the focus. The user should be able to edit the TextBox content without doubleclicking the cell.</strong></p>
  
  <p>I found this article:</p>
  
  <p><a href="http://wpf.codeplex.com/wikipage?title=Single-Click%20Editing&amp;ProjectName=wpf" rel="noreferrer">DataGrid Tips &amp; Tricks: Single-Click Editing</a>
  where I can get the Current DataGridCell, but how can I access the content to give the Textbox the focus to edit the content?</p>
  
  <p>This is my style:</p>
  
  <pre><code>&lt;Style x:Key="CellEditing" TargetType="{x:Type DataGridCell}"&gt;
      &lt;EventSetter Event="PreviewMouseLeftButtonDown" Handler="myDataGridMain_PreviewMouseLeftButtonDown"&gt;&lt;/EventSetter&gt;
  &lt;/Style&gt;
  </code></pre>
  
  <p>This is my event handler:</p>
  
  <pre><code>private void myDataGridMain_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
  {
      DataGridCell cell = sender as DataGridCell;     // cell ist not null
  
      DataGridTemplateColumn col = cell.Column as DataGridTemplateColumn; //col is not null
  
      DataTemplate template = col.CellTemplate;  //this is null
  }
  </code></pre>
  
  <p><strong>How can I get the textbox with that event handler?</strong></p>