Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to perform Single click checkbox selection in WPF DataGrid with IEditableObject object

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?

like image 844
sventevit Avatar asked Sep 07 '25 20:09

sventevit


1 Answers

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}" />
        ...
like image 158
mm8 Avatar answered Sep 11 '25 00:09

mm8