如何使用IEditableObject对象在WPF DataGrid中执行单击复选框选择

时间:2017-03-19 17:14:36

标签: c# wpf mvvm datagrid viewmodel

DataGridCheckBoxColumn的默认行为是用户必须单击两次才能更改复选框值。在How to perform Single click checkbox selection in WPF DataGrid主题中有几个解决方案可行,但存在一个问题 - 您是否在代码后面有一个viewmodel对象,它实现了IEditableObject接口,然后是EndEdit方法不执行。

知道如何进行单击工作并保留IEditableObject功能吗?

2 个答案:

答案 0 :(得分:8)

您可以处理DataGrid的{​​{1}}事件,并明确进入编辑模式并选中/取消选中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}" />
        ...

答案 1 :(得分:1)

对所有复选框使用相同的方法

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;
                }
            }
        }