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

浪尽此生 提交于 2020-04-13 17:54:05

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!