Search This Blog

Friday, May 20, 2016

WPF datagrid edit cell on single click

WPF > DataGrid > Edit cell on single click

<Window.Resources>
        <Style TargetType="{x:Type DataGridCell}">
            <EventSetter Event="PreviewMouseLeftButtonDown"    Handler="DataGridCell_PreviewMouseLeftButtonDown" />
        </Style>
    </Window.Resources>

private void DataGridCell_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
    DataGridCell cell = sender as DataGridCell;
    EditCell(cell, e);
}

private void EditCell(DataGridCell cell, RoutedEventArgs e)
{
    if (cell == null || cell.IsEditing || cell.IsReadOnly)
       return;

    if (!cell.IsFocused)
    {
                cell.Focus();
    }
    DGrid.BeginEdit(e);
    cell.Dispatcher.Invoke(
           DispatcherPriority.Background,
           new Action(delegate { })
    );

}