问题
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?
回答1:
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}" />
...
回答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;
}
}
}
来源:https://stackoverflow.com/questions/42889566/how-to-perform-single-click-checkbox-selection-in-wpf-datagrid-with-ieditableobj