如何在一次单击中禁用行选择并启用复选框

本文关键字:行选 选择 复选框 启用 单击 一次 | 更新日期: 2023-09-27 18:16:56

我试图在WPF MVVM中创建一个数据网格,其中包含行信息和列是代表Boolean属性的DataGridCheckBoxColumn

我希望能够点击一个复选框,并将其更改为'checked'在一次点击。我还想禁用选择行的选项,并禁用更改其他列中的其他内容的选项。

请建议。

如何在一次单击中禁用行选择并启用复选框

使用此答案作为起点:如何在WPF DataGrid中执行单个单击复选框选择?

我做了一些修改,最后是这样的:

WPF

:

<DataGrid.Resources>
  <Style TargetType="{x:Type DataGridRow}">
    <EventSetter Event="PreviewMouseLeftButtonDown" Handler="DataGridRow_PreviewMouseLeftButtonDown"/>
  </Style>
  <Style TargetType="{x:Type DataGridCell}">
    <EventSetter Event="PreviewMouseLeftButtonDown" Handler="DataGridCell_PreviewMouseLeftButtonDown"/>
  </Style>
</DataGrid.Resources>

背后的代码:

    private void DataGridRow_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
    {
        DataGridRow row = sender as DataGridRow;
        if (row == null) return;
        if (row.IsEditing) return;
        if (!row.IsSelected) row.IsSelected = true; // you can't select a single cell in full row select mode, so instead we have to select the whole row
    }
    private void DataGridCell_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
    {
        DataGridCell cell = sender as DataGridCell;
        if (cell == null) return;
        if (cell.IsEditing) return;
        if (!cell.IsFocused) cell.Focus(); // you CAN focus on a single cell in full row select mode, and in fact you HAVE to if you want single click editing.
        //if (!cell.IsSelected) cell.IsSelected = true; --> can't do this with full row select.  You HAVE to do this for single cell selection mode.
    }

试一下,看看它是否符合你的要求。

DataGridCheckBoxColumn默认以这种方式工作。第一次单击选择行或单元格,第二次单击更改复选框状态。有时需要这样做:例如,在使用复选框之前需要调用selection changed事件。为了创建一个复选框列,其中复选框在第一次单击时改变,最好使用DataGridTemplateColumn与checkbox作为单元格模板:

                            <DataGridTemplateColumn Header="ChBoxColumn">
                                <DataGridTemplateColumn.CellTemplate>
                                    <DataTemplate>
                                        <CheckBox Checked="CheckBox_Checked" Unchecked="CheckBox_Unchecked" HorizontalAlignment="Center" VerticalAlignment="Center"></CheckBox>
                                    </DataTemplate>
                                </DataGridTemplateColumn.CellTemplate>
                            </DataGridTemplateColumn>