I have a datagrid in WPF with a DataGridTextColum and a DataGridTemplateColum.
<DataGridTextColumn Width="4*" IsReadOnly="True" x:Name="dataGridColumnDescription"
Header="Description" Binding="{Binding Description}">
</DataGridTextColumn>
<DataGridTemplateColumn CellStyle="{StaticResource CellEditing}" IsReadOnly="False" Width="*" Header="Value"
CellEditingTemplateSelector="{StaticResource myCellEditingTemplateSelectorValue}"
CellTemplateSelector="{StaticResource myCellTemplateSelectorValue}">
</DataGridTemplateColumn>
The CellTemplateSelectors return a DataTemplate with a TextBlock for the the Celltemplate resp. a TextBox for CellEditing!
<DataTemplate x:Key="dGridStringValueTemplate">
<TextBlock HorizontalAlignment="Center" VerticalAlignment="Center" Text="{Binding Path=Value}"/>
</DataTemplate>
<DataTemplate x:Key="dGridStringValueTemplateEditing">
<TextBox TextAlignment="Center" VerticalAlignment="Center" VerticalContentAlignment="Center" HorizontalContentAlignment="Center" BorderThickness="1" Text="{Binding Path=Value, UpdateSourceTrigger=LostFocus}"/>
</DataTemplate>
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.
I found this article:
DataGrid Tips & Tricks: Single-Click Editing where I can get the Current DataGridCell, but how can I access the content to give the Textbox the focus to edit the content?
This is my style:
<Style x:Key="CellEditing" TargetType="{x:Type DataGridCell}">
<EventSetter Event="PreviewMouseLeftButtonDown" Handler="myDataGridMain_PreviewMouseLeftButtonDown"></EventSetter>
</Style>
This is my event handler:
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
}
How can I get the textbox with that event handler?