Skip to content

Instantly share code, notes, and snippets.

@dealproc
Created July 18, 2014 15:38
Show Gist options
  • Save dealproc/c6eb3cde65c595adf49b to your computer and use it in GitHub Desktop.
Save dealproc/c6eb3cde65c595adf49b to your computer and use it in GitHub Desktop.
WPF Datagrid - Edit on focus
namespace {Your.Namespace.Here}.Behaviors {
using System.Windows.Controls;
using System.Windows.Interactivity;
// Pulled from: http://codermonkey65.blogspot.com/2012/12/making-wpf-datagrid-keyboard-friendly.html
public class DataGridAutomaticEditingBehavior : Behavior<DataGrid> {
protected override void OnAttached() {
AssociatedObject.GotFocus += AssociatedObject_GotFocus;
base.OnAttached();
}
void AssociatedObject_GotFocus(object sender, System.Windows.RoutedEventArgs e) {
DataGridCell gridCell = e.OriginalSource as DataGridCell;
if (gridCell != null) {
gridCell.EnterEdit(AssociatedObject);
}
}
}
public static class GridCellExtensions{
public static void EnterEdit(this DataGridCell gridCell, DataGrid grid, bool bFocus = true) {
if (gridCell != null && !gridCell.IsEditing) {
// enables editing on single click
if (!gridCell.IsFocused)
gridCell.Focus();
if (!gridCell.IsSelected && grid.SelectionUnit == DataGridSelectionUnit.Cell)
gridCell.IsSelected = true;
grid.BeginEdit();
if (bFocus) {
gridCell.Focus();
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment