I have a datagrid in WPF with a DataGridTextColum and a DataGridTemplateColum.
I managed it, not the best solution but it works... When Cell gets focus I set it to editing mode.
private void myDataGridMain_OnFocus(object sender, RoutedEventArgs e)
{
DataGridCell cell = sender as DataGridCell;
if (cell != null)
cell.IsEditing = true;
//var test = FindVisualChild(cell);
}
On Keydown I search for the visual child and give the focus.
private void myDataGridMain_KeyDown(object sender, KeyEventArgs e)
{
DataGridCell cell = sender as DataGridCell;
if (e.Key == Key.Enter)
{ //give cell the focus
cell.Focus();
}
else
{
if ((cell != null))
{
TextBox textbox = FindVisualChild(cell);
if (textbox != null)
{ //TextBox has benn found
if ((textbox as TextBox).IsFocused == false)
{
(textbox as TextBox).SelectAll();
}
(textbox as TextBox).Focus();
}
CheckBox chkbox = FindVisualChild(cell);
if (chkbox != null)
{ //Checkbox has been found
(chkbox as CheckBox).Focus();
}
ComboBox combbox = FindVisualChild(cell);
if (combbox != null)
{ //ComboBox has been found
(combbox as ComboBox).Focus();
}
}
}
}
Find Visual Child!
public static T FindVisualChild(DependencyObject obj) where T : DependencyObject
{
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(obj); i++)
{
DependencyObject child = VisualTreeHelper.GetChild(obj, i);
if (child != null && child is T)
return (T)child;
else
{
T childOfChild = FindVisualChild(child);
if (childOfChild != null)
return childOfChild;
}
}
return null;
}