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.
In case of Selected
event, the problem is that it enables single click edit on all columns even though it is handled on just one column (again, set through style):
private void DataGridCell_Selected(object sender, RoutedEventArgs e)
{
// second part of condition is always true, no matter what cell is clicked
if (sender is DataGridCell cell && cell.Column == ItemListDG.Columns[0])
{
// try to detect if the CheckBox column was clicked, if not return
if (sender != e.OriginalSource) // always false
return;
ItemListDG.BeginEdit(e); // always executes no matter the source
}
}