mardi 10 novembre 2020

WPF DataGrid single click CheckBox does not enter Edit mode

I have a DataGrid with CheckBox-type column which should be editable with single click. This is easily achieved by using template column with CheckBox inside:

<DataGridTemplateColumn.CellTemplate>
    <DataTemplate>
        <CheckBox IsChecked="{Binding Path=IsSelected, UpdateSourceTrigger=PropertyChanged}" />
    </DataTemplate>
</DataGridTemplateColumn.CellTemplate>
<DataGridTemplateColumn.CellEditingTemplate>
    <DataTemplate>
        <CheckBox BackGround="Red" IsChecked="{Binding Path=IsSelected, UpdateSourceTrigger=PropertyChanged}" />
    </DataTemplate>
</DataGridTemplateColumn.CellEditingTemplate>

the problem, however, is that single clicking will change the value without ever entering Edit mode. How can I ensure the edit mode is entered before changing the CheckBox value (all will single click)?


My best attempt on the problem was setting PreviewMouseLeftButtonDown on DataGridCell through style and forcing BeginEdit(). While this does begin edit, it is back to needing double click to interact.

private void DataGridCell_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
    if (sender is DataGridCell cell && !cell.IsEditing && e.OriginalSource is DependencyObject source)
    {
        var checkBoxParent = VisualExtensions.GetVisualParent<CheckBox>(source);
        if (checkBoxParent != null) // ensure CheckBox was clicked
        {
            cell.Focus();
            ItemListDG.BeginEdit();
        }
    }
}

I have also tried handling Selected or GotFocus without any luck (breaks other types of interaction), CheckBox.Checked events cannot be used neither because they trigger on re/load.




Aucun commentaire:

Enregistrer un commentaire