3

The default behavior of DataGridCheckBoxColumn is that the user has to click twice to change the checkbox value. In the How to perform Single click checkbox selection in WPF DataGrid topic there are a couple of solutions which work, but there is a problem - is you have a viewmodel object in code behind, which implements the IEditableObject interface, then the EndEdit method doesn't execute.

Any idea how to make single click work and also preserve the IEditableObject functionallity?

Community
  • 1
  • 1
sventevit
  • 4,766
  • 10
  • 57
  • 89

2 Answers2

9

You could handle the GotFocus event for the DataGrid and explicitly enter the edit mode and check/uncheck the CheckBox:

private void dg_GotFocus(object sender, RoutedEventArgs e)
{
    DataGridCell cell = e.OriginalSource as DataGridCell;
    if (cell != null && cell.Column is DataGridCheckBoxColumn)
    {
        dg.BeginEdit();
        CheckBox chkBox = cell.Content as CheckBox;
        if (chkBox != null)
        {
            chkBox.IsChecked = !chkBox.IsChecked;
        }
    }
}

<DataGrid x:Name="dg" AutoGenerateColumns="False" GotFocus="dg_GotFocus">
    <DataGrid.Columns>
        <DataGridCheckBoxColumn Binding="{Binding IsChecked, UpdateSourceTrigger=PropertyChanged}" />
        ...
mm8
  • 163,881
  • 10
  • 57
  • 88
2

to use same method for all checkbox

private void GotFocus(object sender, RoutedEventArgs e)
        {
            var sen = sender as DataGrid;
            DataGridCell cell = e.OriginalSource as DataGridCell;
            if (cell != null && cell.Column is DataGridCheckBoxColumn)
            {
                sen.BeginEdit();
                CheckBox chkBox = cell.Content as CheckBox;
                if (chkBox != null)
                {
                    chkBox.IsChecked = !chkBox.IsChecked;
                }
            }
        }